diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js index 0d4569c601b91..76a6a60e72976 100644 --- a/lib/cancellationToken.js +++ b/lib/cancellationToken.js @@ -49,7 +49,7 @@ function createCancellationToken(args) { }, resetRequest: function (requestId) { if (currentRequestId_1 !== requestId) { - throw new Error("Mismatched request id, expected ".concat(currentRequestId_1, ", actual ").concat(requestId)); + throw new Error("Mismatched request id, expected " + currentRequestId_1 + ", actual " + requestId); } perRequestPipeName_1 = undefined; } diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index e75af197f6507..1df80098b971b 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Experimentální podpora dekorátorů je funkce, která se v budoucí verzi může změnit. Toto upozornění odstraníte nastavením možnosti experimentalDecorators v tsconfig nebo jsconfig.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Explicitně zadaný druh překladu modulu: {0}.", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Pokud není možnost target nastavená na es2016 nebo novější, nedají se hodnoty bigint umocnit.", + "Export_0_from_module_1_90059": "Exportovat {0} z modulu {1}", + "Export_all_referenced_locals_90060": "Exportovat všechny odkazované místní hodnoty", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Přiřazení exportu nelze použít, pokud jsou cílem moduly ECMAScript. Zkuste místo toho použít export default nebo jiný formát modulu.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Když má příznak --module hodnotu system, nepodporuje se přiřazení exportu.", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Konflikty deklarace exportu s exportovanou deklarací {0}", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Vytvořte klíč jenom ze zpětných řetězců místo z řetězců, čísel nebo symbolů (možnost ze starší verze).", "Make_super_call_the_first_statement_in_the_constructor_90002": "Nastavit volání metody super() jako první příkaz v konstruktoru", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Typu mapovaného objektu má implicitně typ šablony any.", + "Matched_0_condition_1_6403": "Odpovídá {0} podmínce {1}", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Porovnává se ve výchozím nastavení se vzorem zahrnutí **/*.", "Matched_by_include_pattern_0_in_1_1407": "Porovnáváno podle vzoru zahrnutí {0} v {1}", "Member_0_implicitly_has_an_1_type_7008": "Člen {0} má implicitně typ {1}.", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Překlad pro modul {0} se našel v mezipaměti umístění {1}.", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "Překlad pro direktivu odkazu na typ {0} se našel v mezipaměti umístění {1}.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "keyof překládejte jen na názvy vlastností s hodnotami typu string (ne čísla ani symboly).", + "Resolving_in_0_mode_with_conditions_1_6402": "Řešení v režimu {0} s podmínkami {1}.", "Resolving_module_0_from_1_6086": "======== Překládá se modul {0} z {1}. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Překládá se název modulu {0} relativní k základní adrese URL {1}–{2}.", "Resolving_real_path_for_0_result_1_6130": "Překládá se skutečná cesta pro {0}, výsledek {1}.", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "Kořenový soubor, který se zadal pro kompilaci", "STRATEGY_6039": "STRATEGIE", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Uložte soubory .tsbuildinfo, aby byla možná přírůstková kompilace projektů.", + "Saw_non_matching_condition_0_6405": "Byla zjištěna neshodná podmínka {0}.", "Scoped_package_detected_looking_in_0_6182": "Zjištěn balíček v oboru, hledání v: {0}", "Selection_is_not_a_valid_statement_or_statements_95155": "Výběr nepředstavuje platný příkaz (platné příkazy).", "Selection_is_not_a_valid_type_node_95133": "Výběr není platným uzlem typů.", @@ -1427,7 +1432,6 @@ "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "Levá strana aritmetické operace musí mít typ any, number, bigint nebo být typu výčtu.", "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "Levá strana výrazu přiřazení nemůže představovat přístup k nepovinné vlastnosti.", "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Levá strana výrazu přiřazení musí být proměnná nebo přístup k vlastnosti.", - "The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or__2360": "Levá strana výrazu in musí být privátní identifikátor nebo typu any, string, number nebo symbol.", "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Levá strana výrazu instanceof musí být typu any, typem objektu nebo parametrem typu.", "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Národní prostředí, které se používá při zobrazování zpráv uživateli (třeba cs-CZ)", "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Maximální hloubka závislostí pro vyhledávání pod node_modules a načítání javascriptových souborů", @@ -1448,7 +1452,6 @@ "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "Návratový typ asynchronní funkce nebo metody musí být globální typ Promise. Zamýšleli jste napsat Promise<{0}>?", "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "Pravá strana příkazu for...in musí být typu any, typem objektu nebo parametrem typu, ale tady má typ {0}.", "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "Pravá strana aritmetické operace musí mít typ any, number, bigint nebo být typu výčtu.", - "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361": "Pravá strana výrazu in nesmí být primitivní typ.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Pravá strana výrazu instanceof musí mít typ any nebo typ, který se dá přiřadit k typu rozhraní Function.", "The_root_value_of_a_0_file_must_be_an_object_5092": "Kořenová hodnota souboru {0} musí být objekt.", "The_shadowing_declaration_of_0_is_defined_here_18017": "Překrývající deklarace {0} je definovaná tady.", @@ -1476,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "Vlastnost {0} této značky JSX očekává jeden podřízený objekt typu {1}, ale poskytlo se jich více.", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "Vlastnost {0} této značky JSX očekává typ {1}, který vyžaduje více podřízených objektů, ale zadal se jen jeden.", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Toto porovnání se zdá být neúmyslné, protože typy {0} a {1} se nijak nepřekrývají.", + "This_condition_will_always_return_0_2845": "Tato podmínka vždy vrátí {0}.", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Tato podmínka vždy vrátí „{0}“, protože JavaScript porovnává objekty pomocí odkazu, nikoli hodnoty.", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Tato podmínka vždy vrátí hodnotu True, protože tato {0} je vždy definovaná.", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Tato podmínka vždy vrátí hodnotu True, protože tato funkce je vždy definována. Chtěli jste ji místo toho nazvat?", @@ -1551,6 +1555,7 @@ "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "Typ {0} se nedá přiřadit k typu {1} s hodnotou exactOptionalPropertyTypes: true. Zvažte možnost přidat hodnotu undefined do typu cíle.", "Type_0_is_not_comparable_to_type_1_2678": "Typ {0} se nedá porovnat s typem {1}.", "Type_0_is_not_generic_2315": "Typ {0} není obecný.", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "Typ {0} může představovat primitivní hodnotu, která není povolena jako pravý operand operátoru in.", "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Typ {0} musí mít metodu [Symbol.asyncIterator](), která vrací asynchronní iterátor.", "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Typ {0} musí mít metodu [Symbol.iterator](), která vrací iterátor.", "Type_0_provides_no_match_for_the_signature_1_2658": "Typ {0} neposkytuje žádnou shodu pro podpis {1}.", @@ -1649,9 +1654,12 @@ "Updating_output_of_project_0_6373": "Aktualizuje se výstup projektu {0}...", "Updating_output_timestamps_of_project_0_6359": "Aktualizují se výstupní časová razítka projektu {0}...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Aktualizují se nezměněná výstupní časová razítka projektu {0}...", + "Use_0_95174": "Použít {0}", + "Use_Number_isNaN_in_all_conditions_95175": "Ve všech podmínkách použijte Number.isNaN.", "Use_element_access_for_0_95145": "Použít přístup k elementům pro {0}", "Use_element_access_for_all_undeclared_properties_95146": "Použít přístup k elementům pro všechny nedeklarované vlastnosti", "Use_synthetic_default_member_95016": "Použije syntetického výchozího člena.", + "Using_0_subpath_1_with_target_2_6404": "Používá se {0} dílčí cesta {1} s cílem {2}.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Použití řetězce v příkazu for...of se podporuje jenom v ECMAScript 5 nebo vyšší verzi.", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Použití --build, -b způsobí, že se tsc bude chovat spíše jako orchestrátor sestavení než kompilátor. Pomocí této možnosti můžete aktivovat vytváření složených projektů, o kterých se můžete dozvědět více {0}", "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 7a87b1eebfe35..8aa99fe93125a 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Die experimentelle Unterstützung für decorator-Elemente ist ein Feature, das in zukünftigen Versionen Änderungen unterliegt. Legen Sie die Option \"-experimentalDecorators\" in Ihrer \"tsconfig\" oder \"jsconfig\" fest, um diese Warnung zu entfernen.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Explizit angegebene Art der Modulauflösung: \"{0}\".", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Die Potenzierung kann für bigint-Werte nur durchgeführt werden, wenn die Option \"target\" auf \"es2016\" oder höher festgelegt ist.", + "Export_0_from_module_1_90059": "Exportieren von \"{0}\" aus Modul \"{1}\"", + "Export_all_referenced_locals_90060": "Alle referenzierten lokalen Elemente exportieren", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Die Exportzuweisung darf nicht verwendet werden, wenn das Ziel ECMAScript-Module sind. Verwenden Sie stattdessen ggf. \"export default\" oder ein anderes Modulformat.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Die Exportzuweisung wird nicht unterstützt, wenn das Flag \"-module\" den Wert \"system\" aufweist.", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Die Exportdeklaration verursacht einen Konflikt mit der exportierten Deklaration von \"{0}\".", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Stellen Sie ein, dass keyof nur Zeichenfolgen, anstelle von Zeichenfolgen, Zahlen oder Symbolen zurückgibt. Legacy-Option.", "Make_super_call_the_first_statement_in_the_constructor_90002": "super()-Aufruf als erste Anweisung im Konstruktor festlegen", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Der zugeordnete Objekttyp weist implizit einen any-Vorlagentyp auf.", + "Matched_0_condition_1_6403": "Übereinstimmung mit \"{0}\" Bedingung \"{1}\".", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Standardmäßig zugeordnetes Includemuster „**/*“", "Matched_by_include_pattern_0_in_1_1407": "Abgeglichen mit dem include-Muster \"{0}\" in \"{1}\"", "Member_0_implicitly_has_an_1_type_7008": "Der Member \"{0}\" weist implizit den Typ \"{1}\" auf.", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Die Auflösung für das Modul \"{0}\" wurde im Cache des Standorts \"{1}\" gefunden.", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "Die Auflösung für die Typreferenzanweisung \"{0}\" wurde im Cache des Standorts \"{1}\" gefunden.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "\"keyof\" darf nur in Eigenschaftennamen mit Zeichenfolgenwert aufgelöst werden (keine Ziffern oder Symbole).", + "Resolving_in_0_mode_with_conditions_1_6402": "Wird im {0}-Modus mit Bedingungen \"{1}\" aufgelöst.", "Resolving_module_0_from_1_6086": "======== Das Modul \"{0}\" aus \"{1}\" wird aufgelöst. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Der Modulname \"{0}\" relativ zur Basis-URL \"{1}\"–\"{2}\" wird aufgelöst.", "Resolving_real_path_for_0_result_1_6130": "Der tatsächliche Pfad für \"{0}\" wird aufgelöst, Ergebnis \"{1}\".", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "Für die Kompilierung angegebene Stammdatei", "STRATEGY_6039": "STRATEGIE", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Speichern Sie die .tsbuildinfo-Dateien, um eine inkrementelle Kompilierung von Projekten zuzulassen.", + "Saw_non_matching_condition_0_6405": "Die nicht übereinstimmende Bedingung \"{0}\" wurde angezeigt.", "Scoped_package_detected_looking_in_0_6182": "Bereichsbezogenes Paket erkannt. In \"{0}\" wird gesucht", "Selection_is_not_a_valid_statement_or_statements_95155": "Die Auswahl umfasst keine gültigen Anweisungen.", "Selection_is_not_a_valid_type_node_95133": "Die Auswahl ist kein gültiger Typknoten.", @@ -1474,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "Die Eigenschaft \"{0}\" für dieses JSX-Tag erwartet ein einzelnes untergeordnetes Element vom Typ \"{1}\", aber es wurden mehrere untergeordnete Elemente angegeben.", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "Die Eigenschaft \"{0}\" für dieses JSX-Tag erwartet den Typ \"{1}\", der mehrere untergeordnete Elemente erfordert, aber es wurde nur ein untergeordnetes Elemente angegeben.", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Dieser Vergleich scheint unbeabsichtigt zu sein, da die Typen \"{0}\" und \"{1}\" keine Überlappung aufweisen.", + "This_condition_will_always_return_0_2845": "Diese Bedingung gibt immer „{0}“ zurück.", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Diese Bedingung gibt immer „{0}“ zurück, da JavaScript Objekte nach Verweis und nicht nach Wert vergleicht.", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Diese Bedingung gibt immer TRUE zurück, weil diese '{0}' immer definiert ist.", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Diese Bedingung gibt immer TRUE zurück, weil diese Funktion immer definiert ist. Möchten Sie sie stattdessen aufrufen?", @@ -1648,9 +1654,12 @@ "Updating_output_of_project_0_6373": "Ausgabe von Projekt \"{0}\" wird aktualisiert...", "Updating_output_timestamps_of_project_0_6359": "Ausgabezeitstempel von Projekt \"{0}\" werden aktualisiert...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Unveränderte Ausgabezeitstempel von Projekt \"{0}\" werden aktualisiert...", + "Use_0_95174": "Verwenden Sie „{0}“.", + "Use_Number_isNaN_in_all_conditions_95175": "Verwenden Sie „Number.isNaN“ unter allen Bedingungen.", "Use_element_access_for_0_95145": "Elementzugriff für \"{0}\" verwenden", "Use_element_access_for_all_undeclared_properties_95146": "Elementzugriff für alle nicht deklarierten Eigenschaften verwenden", "Use_synthetic_default_member_95016": "Verwenden Sie den synthetischen Member \"default\".", + "Using_0_subpath_1_with_target_2_6404": "Verwenden von \"{0}\" Unterpfad \"{1}\" mit Ziel \"{2}\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Das Verwenden einer Zeichenfolge in einer for...of-Anweisung wird nur in ECMAScript 5 oder höher unterstützt.", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Bei Verwendung von --build wird tsc durch -b dazu veranlasst, sich eher wie ein Build-Orchestrator als ein Compiler zu verhalten. Damit wird der Aufbau von zusammengesetzten Projekten ausgelöst. Weitere Informationen dazu finden Sie unter {0}", "Using_compiler_options_of_project_reference_redirect_0_6215": "Compileroptionen der Projektverweisumleitung \"{0}\" werden verwendet.", diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 2d36e561a3e12..242b20b06435c 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "La compatibilidad experimental con los decoradores es una característica que está sujeta a cambios en una próxima versión. Establezca la opción \"experimentalDecorators\" en \"tsconfig\" o \"jsconfig\" para quitar esta advertencia.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Tipo de resolución de módulo especificado de forma explícita: '{0}'.", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "No se puede realizar la exponenciación en los valores \"bigint\", a menos que la opción \"target\" esté establecida en \"es2016\" o posterior.", + "Export_0_from_module_1_90059": "Exportar '{0}' desde el módulo '{1}'", + "Export_all_referenced_locals_90060": "Exportar todas las variables locales a las que se hace referencia", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "No se puede usar una asignación de exportación cuando se eligen módulos de ECMAScript como destino. Considere la posibilidad de usar \"export default\" u otro formato de módulo en su lugar.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "La asignación de exportación no es compatible cuando la marca \"--module\" es \"system\".", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La declaración de exportación está en conflicto con la declaración exportada de \"{0}\".", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Haga que keyof solo devuelva cadenas en lugar de cadenas, números o símbolos. Opción heredada.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Hacer que la llamada a \"super()\" sea la primera instrucción del constructor", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "El tipo de objeto asignado tiene implícitamente un tipo de plantilla \"any\".", + "Matched_0_condition_1_6403": "Coincidente con '{0}' condición '{1}'.", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "La coincidencia de forma predeterminada incluye el patrón '**/*'", "Matched_by_include_pattern_0_in_1_1407": "Coincidencia con el patrón de inclusión \"{0}\" en \"{1}\"", "Member_0_implicitly_has_an_1_type_7008": "El miembro '{0}' tiene un tipo '{1}' implícitamente.", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La resolución del módulo \"{0}\" se encontró en la memoria caché de la ubicación \"{1}\".", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "La resolución de la directiva de referencia de tipo \"{0}\" se encontró en la memoria caché de la ubicación \"{1}\".", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolver \"keyof\" exclusivamente como nombres de propiedad con valores de cadena (sin números ni símbolos).", + "Resolving_in_0_mode_with_conditions_1_6402": "Resolviendo en modo {0} con condiciones {1}.", "Resolving_module_0_from_1_6086": "======== Resolviendo el módulo '{0}' de '{1}'. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolviendo el nombre de módulo '{0}' relativo a la dirección URL base '{1}' - '{2}'.", "Resolving_real_path_for_0_result_1_6130": "Resolviendo la ruta de acceso real de \"{0}\", resultado: \"{1}\".", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "Archivo raíz especificado para la compilación", "STRATEGY_6039": "ESTRATEGIA", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Guarde archivos .tsbuildinfo para permitir la compilación incremental de proyectos.", + "Saw_non_matching_condition_0_6405": "Se vio una condición no coincidente '{0}'.", "Scoped_package_detected_looking_in_0_6182": "Se detectó un paquete con ámbito al buscar en \"{0}\"", "Selection_is_not_a_valid_statement_or_statements_95155": "La selección no es una instrucción ni instrucciones válidas", "Selection_is_not_a_valid_type_node_95133": "La selección no es un nodo de tipo válido", @@ -1474,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "La propiedad \"{0}\" de esta etiqueta de JSX espera un solo elemento secundario de tipo \"{1}\", pero se han proporcionado varios elementos secundarios.", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "La propiedad \"{0}\" de esta etiqueta de JSX espera el tipo \"{1}\", que requiere varios elementos secundarios, pero solo se ha proporcionado un elemento secundario.", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Esta comparación parece no intencionada porque los tipos \"{0}\" y \"{1}\" no tienen superposición.", + "This_condition_will_always_return_0_2845": "Esta condición siempre devolverá \"{0}\".", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Esta condición siempre devolverá \"{0}\", ya que JavaScript compara objetos por referencia, no por valor.", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Esta condición devolverá siempre true porque siempre se define '{0}'.", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Esta condición siempre devolverá true, porque esta función se define siempre. ¿Pretendía llamarla en su lugar?", @@ -1648,9 +1654,12 @@ "Updating_output_of_project_0_6373": "Actualizando la salida del proyecto \"{0}\"...", "Updating_output_timestamps_of_project_0_6359": "Actualizando las marcas de hora de salida del proyecto \"{0}\"...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Actualizando las marcas de hora de salida no modificadas del proyecto \"{0}\"...", + "Use_0_95174": "Usar `{0}`.", + "Use_Number_isNaN_in_all_conditions_95175": "Use \"Number.isNaN\" en todas las condiciones.", "Use_element_access_for_0_95145": "Usar acceso de elemento para \"{0}\"", "Use_element_access_for_all_undeclared_properties_95146": "Use el acceso de elemento para todas las propiedades no declaradas.", "Use_synthetic_default_member_95016": "Use el miembro sintético \"default\".", + "Using_0_subpath_1_with_target_2_6404": "Usando '{0}' subruta '{1}' con destino '{2}'.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "El uso de una cadena en una instrucción \"for...of\" solo se admite en ECMAScript 5 y versiones posteriores.", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Con --build, -b hará que tsc se comporte más como un orquestador de compilación que como un compilador. Se usa para desencadenar la compilación de proyectos compuestos, sobre los que puede obtener más información en {0}", "Using_compiler_options_of_project_reference_redirect_0_6215": "Uso de las opciones del compilador de redireccionamiento de la referencia del proyecto \"{0}\".", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 2a520a280a134..b962857b712d0 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "La prise en charge expérimentale des éléments décoratifs est une fonctionnalité susceptible de changer dans une prochaine version. Définissez l'option 'experimentalDecorators' dans votre fichier 'tsconfig' ou 'jsconfig' pour supprimer cet avertissement.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Spécification explicite du genre de résolution de module : '{0}'.", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Impossible d'effectuer l'élévation à une puissance sur des valeurs 'bigint' sauf si l'option 'target' a la valeur 'es2016' ou une valeur qui correspond à une version ultérieure.", + "Export_0_from_module_1_90059": "Exporter '{0}' à partir du module '{1}'", + "Export_all_referenced_locals_90060": "Exporter tous les variables locales référencées", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Vous ne pouvez pas utiliser l'assignation d'exportation pour cibler des modules ECMAScript. Utilisez 'export default' ou un autre format de module à la place.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "L'assignation d'exportation n'est pas prise en charge quand l'indicateur '--module' est 'system'.", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La déclaration d'exportation est en conflit avec la déclaration exportée de '{0}'.", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Faites en sorte que keyof retourne uniquement des chaînes au lieu de chaînes, de nombres ou de symboles. Option héritée.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Faire de l'appel à 'super()' la première instruction du constructeur", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Le type d'objet mappé a implicitement un type de modèle 'any'.", + "Matched_0_condition_1_6403": "Condition '{0}' correspondant à '{1}'.", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Mise en correspondance par défaut du modèle include '**/*'", "Matched_by_include_pattern_0_in_1_1407": "Correspond au modèle include '{0}' dans '{1}'", "Member_0_implicitly_has_an_1_type_7008": "Le membre '{0}' possède implicitement un type '{1}'.", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La résolution du module '{0}' a été trouvée dans le cache à l'emplacement '{1}'.", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "La résolution de la directive de référence de type '{0}' a été trouvée dans le cache à l'emplacement '{1}'.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Résoudre 'keyof' en noms de propriétés de valeur chaîne uniquement (aucun nombre ou symbole).", + "Resolving_in_0_mode_with_conditions_1_6402": "Résolution en mode {0} avec des conditions {1}.", "Resolving_module_0_from_1_6086": "======== Résolution du module '{0}' à partir de '{1}'. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Résolution du nom de module '{0}' par rapport à l'URL de base '{1}' - '{2}'.", "Resolving_real_path_for_0_result_1_6130": "Résolution du chemin réel pour '{0}', résultat '{1}'.", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "Fichier racine spécifié pour la compilation", "STRATEGY_6039": "STRATÉGIE", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Enregistrez les fichiers .tsbuildinfo pour permettre la compilation incrémentielle des projets.", + "Saw_non_matching_condition_0_6405": "Condition non correspondante '{0}' visible.", "Scoped_package_detected_looking_in_0_6182": "Package de portée détecté. Recherche dans '{0}'", "Selection_is_not_a_valid_statement_or_statements_95155": "La sélection ne correspond pas à une ou des instructions valides", "Selection_is_not_a_valid_type_node_95133": "La sélection n'est pas un nœud de type valide", @@ -1427,7 +1432,6 @@ "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "La partie gauche d'une opération arithmétique doit être de type 'any', 'number', 'bigint' ou un type enum.", "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "La partie gauche d'une expression d'assignation ne doit pas être un accès à une propriété facultative.", "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La partie gauche d'une expression d'assignation doit être un accès à une variable ou une propriété.", - "The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or__2360": "La partie gauche d'une expression 'in' doit être un identificateur privé ou de type 'any', 'string', 'number' ou 'symbol'.", "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La partie gauche d'une expression 'instanceof' doit être de type 'any', un type d'objet ou un paramètre de type.", "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Paramètres régionaux utilisés pour afficher les messages à l'utilisateur (exemple : 'fr-fr')", "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Profondeur de dépendance maximale pour la recherche sous node_modules et le chargement de fichiers JavaScript.", @@ -1448,7 +1452,6 @@ "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "Le type de retour d'une fonction ou d'une méthode asynchrone doit être le type global Promise. Vouliez-vous vraiment écrire 'Promise<{0}>' ?", "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "La partie droite d'une instruction 'for...in' doit être de type 'any', un type d'objet ou un paramètre de type, mais elle a le type '{0}' ici.", "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "La partie droite d'une opération arithmétique doit être de type 'any', 'number', 'bigint' ou un type enum.", - "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361": "La partie droite d'une expression 'in' ne doit pas être une primitive.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La partie droite d'une expression 'instanceof' doit être de type 'any' ou d'un type pouvant être assigné au type d'interface 'Function'.", "The_root_value_of_a_0_file_must_be_an_object_5092": "La valeur racine d'un fichier '{0}' doit être un objet.", "The_shadowing_declaration_of_0_is_defined_here_18017": "La déclaration avec mise en mémoire fantôme de '{0}' est définie ici", @@ -1476,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "La propriété '{0}' de cette balise JSX attend un seul enfant de type '{1}', mais plusieurs enfants ont été fournis.", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "La propriété '{0}' de cette balise JSX attend le type '{1}', qui nécessite plusieurs enfants, mais un seul enfant a été fourni.", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Cette comparaison semble involontaire, car les types '{0}' et '{1}' n’ont pas de chevauchement.", + "This_condition_will_always_return_0_2845": "Cette condition retourne toujours '{0}'.", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Cette condition retourne toujours '{0}', car JavaScript compare les objets par référence, et non par valeur.", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Cette condition retourne toujours true, car cette « {0} » est toujours définie.", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Cette condition retourne toujours true, car cette fonction est toujours définie. Est-ce que vous avez voulu l'appeler à la place ?", @@ -1551,6 +1555,7 @@ "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "Le type '{0}' n'est pas assignable au type '{1}' avec 'exactOptionalPropertyTypes : true'. Pensez à ajouter 'undefined' au type de la cible.", "Type_0_is_not_comparable_to_type_1_2678": "Le type '{0}' n'est pas comparable au type '{1}'.", "Type_0_is_not_generic_2315": "Le type '{0}' n'est pas générique.", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "Le type '{0}' peut représenter une valeur primitive, ce qui n’est pas autorisé en tant qu’opérande droit de l’opérateur 'in'.", "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Le type '{0}' doit avoir une méthode '[Symbol.asyncIterator]()' qui retourne un itérateur asynchrone.", "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Le type '{0}' doit avoir une méthode '[Symbol.iterator]()' qui retourne un itérateur.", "Type_0_provides_no_match_for_the_signature_1_2658": "Le type '{0}' ne fournit aucune correspondance pour la signature '{1}'.", @@ -1649,9 +1654,12 @@ "Updating_output_of_project_0_6373": "Mise à jour de la sortie du projet '{0}'...", "Updating_output_timestamps_of_project_0_6359": "Mise à jour des horodatages de sortie du projet '{0}'...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Mise à jour des horodatages de sortie inchangés du projet '{0}'...", + "Use_0_95174": "Utilisez `{0}`.", + "Use_Number_isNaN_in_all_conditions_95175": "Utilisez 'Number.isNaN' dans toutes les conditions.", "Use_element_access_for_0_95145": "Utiliser l'accès à l'élément pour '{0}'", "Use_element_access_for_all_undeclared_properties_95146": "L'accès à l'élément est utilisé pour toutes les propriétés non déclarées.", "Use_synthetic_default_member_95016": "Utilisez un membre 'default' synthétique.", + "Using_0_subpath_1_with_target_2_6404": "Utilisation de '{0}' de sous-chemin '{1}' avec la cible '{2}'.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'utilisation d'une chaîne dans une instruction 'for...of' est prise en charge uniquement dans ECMAScript 5 et version supérieure.", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "L’utilisation de--build,-b fera en sorte que tsc se comporte plus comme une build orchestrateur qu’un compilateur. Utilisé pour déclencher la génération de projets composites sur lesquels vous pouvez obtenir des informations supplémentaires sur {0}", "Using_compiler_options_of_project_reference_redirect_0_6215": "Utilisation des options de compilateur de la redirection de référence de projet : '{0}'.", diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json index d5cf261116550..2acc6530a8ace 100644 --- a/lib/it/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Il supporto sperimentale per gli elementi Decorator è una funzionalità soggetta a modifica nelle prossime versioni. Per rimuovere questo avviso, impostare l'opzione 'experimentalDecorators' nel file 'tsconfig' o 'jsconfig'.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Il tipo di risoluzione del modulo '{0}' è stato specificato in modo esplicito.", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Non è possibile usare l'elevamento a potenza su valori 'bigint' a meno che l'opzione 'target' non sia impostata su 'es2016' o versioni successive.", + "Export_0_from_module_1_90059": "Esporta '{0}' dal modulo '{1}'", + "Export_all_referenced_locals_90060": "Esporta tutte le variabili locali di riferimento", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Non è possibile usare l'assegnazione di esportazione se destinata a moduli ECMAScript. Provare a usare 'export default' o un altro formato di modulo.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "L'assegnazione dell'esportazione non è supportata quando il valore del flag '--module' è 'system'.", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "La dichiarazione di esportazione è in conflitto con la dichiarazione esportata di '{0}'.", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Imposta keyof in modo che restituisca solo stringhe invece di stringhe, numeri o simboli. Opzione legacy.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Impostare la chiamata a 'super()' come prima istruzione nel costruttore", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Il tipo di oggetto con mapping contiene implicitamente un tipo di modello 'any'.", + "Matched_0_condition_1_6403": "Corrispondenza tra '{0}' condizione '{1}'.", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Corrispondente per impostazione predefinita al criterio di inclusione '**/*'", "Matched_by_include_pattern_0_in_1_1407": "Corrispondenza tramite criterio di inclusione '{0}' in '{1}'", "Member_0_implicitly_has_an_1_type_7008": "Il membro '{0}' contiene implicitamente un tipo '{1}'.", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "La risoluzione per il modulo '{0}' è stata trovata nella cache dal percorso '{1}'.", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "La risoluzione per la direttiva '{0}' del riferimento al tipo è stata trovata nella cache dal percorso '{1}'.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Risolvere 'keyof' solo in nomi di proprietà con valori stringa (senza numeri o simboli).", + "Resolving_in_0_mode_with_conditions_1_6402": "Risoluzione in modalità {0} con condizioni {1}.", "Resolving_module_0_from_1_6086": "======== Risoluzione del modulo '{0}' da '{1}'. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Verrà eseguita la risoluzione del nome del modulo '{0}' relativo all'URL di base '{1}' - '{2}'.", "Resolving_real_path_for_0_result_1_6130": "Risoluzione del percorso reale per '{0}'. Risultato: '{1}'.", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "File radice specificato per la compilazione", "STRATEGY_6039": "STRATEGIA", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Salva i file .tsbuildinfo per consentire la compilazione incrementale dei progetti.", + "Saw_non_matching_condition_0_6405": "Visualizzata la condizione di corrispondenza '{0}'.", "Scoped_package_detected_looking_in_0_6182": "Il pacchetto con ambito è stato rilevato. Verrà eseguita una ricerca in '{0}'", "Selection_is_not_a_valid_statement_or_statements_95155": "La selezione non corrisponde a una o più istruzioni valide", "Selection_is_not_a_valid_type_node_95133": "La selezione non corrisponde a un nodo di tipo valido", @@ -1427,7 +1432,6 @@ "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "La parte sinistra di un'operazione aritmetica deve essere di tipo 'any', 'number', 'bigint' o un tipo enumerazione.", "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "La parte sinistra di un'espressione di assegnazione non può essere un accesso a proprietà facoltativo.", "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "La parte sinistra di un'espressione di assegnazione deve essere una variabile o un accesso a proprietà.", - "The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or__2360": "La parte sinistra di un'espressione 'in' deve essere un identificatore privato o di tipo 'any', 'string', 'number' o 'symbol'.", "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "La parte sinistra di un'espressione 'instanceof' deve essere di tipo 'any' oppure essere un tipo di oggetto o un parametro di tipo.", "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Impostazioni locali usate per la visualizzazione di messaggi all'utente, ad esempio 'it-it'", "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Profondità massima delle dipendenze per la ricerca in node_modules e il caricamento dei file JavaScript.", @@ -1448,7 +1452,6 @@ "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "Il tipo restituito di un metodo o una funzione asincrona deve essere il tipo globale Promise. Si intendeva scrivere 'Promise<{0}>'?", "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "La parte destra di un'istruzione 'for...in' deve essere di tipo 'any' oppure essere un tipo di oggetto o un parametro di tipo, ma in questo caso il tipo è '{0}'.", "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "La parte destra di un'operazione aritmetica deve essere di tipo 'any', 'number', 'bigint' o un tipo enumerazione.", - "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361": "La parte destra di un'espressione 'in' non deve essere una primitiva.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "La parte destra di un'espressione 'instanceof' deve essere di tipo 'any' o di un tipo assegnabile al tipo di interfaccia 'Function'.", "The_root_value_of_a_0_file_must_be_an_object_5092": "Il valore radice di un file '{0}' deve essere un oggetto.", "The_shadowing_declaration_of_0_is_defined_here_18017": "La dichiarazione di oscuramento di '{0}' viene definita in questo punto", @@ -1476,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "Con la proprietà '{0}' del tag JSX è previsto un singolo elemento figlio di tipo '{1}', ma sono stati specificati più elementi figlio.", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "Con la proprietà '{0}' del tag JSX è previsto il tipo '{1}' che richiede più elementi figlio, ma è stato specificato un singolo elemento figlio.", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Questo confronto sembra non intenzionale perché i tipi '{0}' e '{1}' non presentano alcuna sovrapposizione.", + "This_condition_will_always_return_0_2845": "Questa condizione restituirà sempre '{0}'.", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Questa condizione restituirà sempre '{0}' perché JavaScript confronta gli oggetti per riferimento, non per valore.", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Questa condizione restituirà sempre true perché questo elemento '{0}' è sempre definito.", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Questa condizione restituirà sempre true perché questa funzione è sempre definita. Si intendeva chiamarla?", @@ -1551,6 +1555,7 @@ "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "L'argomento di tipo '{0}' non può essere assegnato al tipo '{1}' con 'exactOptionalPropertyTypes: true'. Provare ad aggiungere 'undefined' al tipo di destinazione.", "Type_0_is_not_comparable_to_type_1_2678": "Il tipo '{0}' non è confrontabile con il tipo '{1}'.", "Type_0_is_not_generic_2315": "Il tipo '{0}' non è generico.", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "Il tipo '{0}' può rappresentare un valore primitivo, che non è consentito come operando destro dell'operatore 'in'.", "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Il tipo '{0}' deve contenere un metodo '[Symbol.asyncIterator]()' che restituisce un iteratore asincrono.", "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Il tipo '{0}' deve contenere un metodo '[Symbol.iterator]()' che restituisce un iteratore.", "Type_0_provides_no_match_for_the_signature_1_2658": "Il tipo '{0}' non fornisce corrispondenze per la firma '{1}'.", @@ -1649,9 +1654,12 @@ "Updating_output_of_project_0_6373": "Aggiornamento dell'output del progetto '{0}'...", "Updating_output_timestamps_of_project_0_6359": "Aggiornamento dei timestamp di output del progetto '{0}'...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Aggiornamento dei timestamp di output non modificati del progetto '{0}'...", + "Use_0_95174": "Usa `{0}`.", + "Use_Number_isNaN_in_all_conditions_95175": "Usare 'Number.isNaN' in tutte le condizioni.", "Use_element_access_for_0_95145": "Usare l'accesso agli elementi per '{0}'", "Use_element_access_for_all_undeclared_properties_95146": "Usare l'accesso agli elementi per tutte le proprietà non dichiarate.", "Use_synthetic_default_member_95016": "Usare il membro 'default' sintetico.", + "Using_0_subpath_1_with_target_2_6404": "Utilizzo di '{0}' sottotracciato '{1}' con destinazione '{2}'.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'uso di una stringa in un'istruzione 'for...of' è supportato solo in ECMAScript 5 e versioni successive.", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Se si usa --build, l'opzione -b modificherà il comportamento di tsc in modo che sia più simile a un agente di orchestrazione di compilazione che a un compilatore. Viene usata per attivare la compilazione di progetti compositi. Per altre informazioni, vedere {0}", "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index 33c8b7142a602..5bc780d7a9239 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "デコレーターの実験的なサポートは将来のリリースで変更になる可能性がある機能です。'tsconfig' または 'jsconfig' に 'experimentalDecorators' オプションを設定してこの警告を削除します。", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "明示的に指定されたモジュール解決の種類 '{0}'。", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "'target' オプションが 'es2016' 以降に設定されている場合を除き、'bigint' 値に対して累乗を実行することはできません。", + "Export_0_from_module_1_90059": "'{0}' をモジュール '{1}' からエクスポートする", + "Export_all_referenced_locals_90060": "参照されているすべてのローカルをエクスポートする", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート代入を使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "代入のエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "エクスポート宣言が、'{0}' のエクスポートされた宣言と競合しています。", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "keyof により、文字列、数字、記号の代わりに、文字列のみが返されるようにします。レガシ オプションです。", "Make_super_call_the_first_statement_in_the_constructor_90002": "'super()' 呼び出しをコンストラクター内の最初のステートメントにする", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "マップされたオブジェクト型のテンプレートの型は暗黙的に 'any' になります。", + "Matched_0_condition_1_6403": "'{0}' 条件 '{1}' と一致しました。", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "既定で一致するインクルード パターン '**/*'", "Matched_by_include_pattern_0_in_1_1407": "'{1}' のインクルード パターン '{0}' に一致しています", "Member_0_implicitly_has_an_1_type_7008": "メンバー '{0}' の型は暗黙的に '{1}' になります。", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "モジュール '{0}' の解決が場所 '{1}' のキャッシュに見つかりました。", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "種類参照指令 '{0}' の解決策は、場所 '{1}' のキャッシュには見つかりませんでした。", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'keyof' を文字列値のプロパティ名のみに解決します (数字または記号なし)。", + "Resolving_in_0_mode_with_conditions_1_6402": "条件 {1} を使用して {0} モードで解決しています。", "Resolving_module_0_from_1_6086": "======== '{1}' からモジュール '{0}' を解決しています。========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "ベース URL '{1}' - '{2}' に相対するモジュール名 '{0}' を解決しています。", "Resolving_real_path_for_0_result_1_6130": "'{0}' の実際のパスを解決しています。結果は '{1}' です。", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "コンパイル用に指定されたルート ファイル", "STRATEGY_6039": "戦略", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "プロジェクトのインクリメンタル コンパイルを可能にするには、.tsbuildinfo ファイルを保存します。", + "Saw_non_matching_condition_0_6405": "一致しない条件 '{0}' がありました。", "Scoped_package_detected_looking_in_0_6182": "'{0}' 内を検索して、スコープ パッケージが検出されました", "Selection_is_not_a_valid_statement_or_statements_95155": "選択内容は有効なステートメントではありません", "Selection_is_not_a_valid_type_node_95133": "選択は有効な型ノードではありません", @@ -1474,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "この JSX タグの '{0}' prop は型 '{1}' の単一の子を予期しますが、複数の子が指定されました。", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "この JSX タグの '{0}' prop は複数の子を必要とする型 '{1}' を予期しますが、単一の子が指定されました。", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "'{0}' 型と '{1}' 型が重複していないため、この比較は意図したとおりに表示されない可能性があります。", + "This_condition_will_always_return_0_2845": "この条件は常に '{0}' を返します。", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "JavaScript が値ではなく参照でオブジェクトを比較するため、この条件は常に '{0}' を返します。", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "'{0}' が常に定義されているため、この条件は常に true を返します。", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "この関数は常に定義されているため、この条件は常に true を返します。代わりにこれを呼び出すことを意図していましたか?", @@ -1648,9 +1654,12 @@ "Updating_output_of_project_0_6373": "プロジェクト '{0}' の出力を更新しています...", "Updating_output_timestamps_of_project_0_6359": "プロジェクト '{0}' の出力タイムスタンプを更新しています...", "Updating_unchanged_output_timestamps_of_project_0_6371": "プロジェクト '{0}' の変更されていない出力タイムスタンプを更新しています...", + "Use_0_95174": "\"{0}\" を使用します。", + "Use_Number_isNaN_in_all_conditions_95175": "すべての条件で 'Number.isNaN' を使用します。", "Use_element_access_for_0_95145": "'{0}' に要素アクセスを使用する", "Use_element_access_for_all_undeclared_properties_95146": "宣言されていないすべてのプロパティに対して要素アクセスを使用します。", "Use_synthetic_default_member_95016": "合成 'default' メンバーを使用します。", + "Using_0_subpath_1_with_target_2_6404": "'{0}' サブパス '{1}' をターゲット '{2}' と共に使用しています。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' ステートメントでの文字列の使用は ECMAScript 5 以上でのみサポートされています。", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "--build を使用すると、-b は tsc をコンパイラというよりビルド オーケストレーターのように動作させます。これは、複合プロジェクトのビルドをトリガーするために使用されます。詳細については、{0} を参照してください。", "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index 4d9732bbcff26..3fba8e28eeac6 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "데코레이터에 대한 실험적 지원 기능은 이후 릴리스에서 변경될 수 있습니다. 이 경고를 제거하려면 'tsconfig' 또는 'jsconfig'에서 'experimentalDecorators' 옵션을 설정합니다.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "명시적으로 지정된 모듈 확인 종류 '{0}'입니다.", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "'target' 옵션이 'es2016' 이상으로 설정되어 있지 않으면 'bigint' 값에 지수화를 수행할 수 없습니다.", + "Export_0_from_module_1_90059": "'{0}'을(를) '{1}' 모듈에서 내보냅니다.", + "Export_all_referenced_locals_90060": "참조된 모든 로컬 내보내기", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript 모듈을 대상으로 하는 경우 내보내기 할당을 사용할 수 없습니다. 대신 'export default'나 다른 모듈 형식의 사용을 고려하세요.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "'--module' 플래그가 'system'이면 내보내기 할당은 지원되지 않습니다.", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "내보내기 선언이 '{0}'의 내보낸 선언과 충돌합니다.", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "keyof가 문자열, 숫자 또는 기호 대신 문자열만 반환하도록 합니다. 레거시 옵션입니다.", "Make_super_call_the_first_statement_in_the_constructor_90002": "생성자의 첫 번째 문을 'super()'로 호출", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "매핑된 개체 형식에는 'any' 템플릿 형식이 암시적으로 포함됩니다.", + "Matched_0_condition_1_6403": "'{0}' 조건 '{1}'과(와) 일치합니다.", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "기본적으로 일치되는 포함 패턴 '**/*'", "Matched_by_include_pattern_0_in_1_1407": "'{1}'의 포함 패턴 '{0}'(으)로 일치되었습니다.", "Member_0_implicitly_has_an_1_type_7008": "'{0}' 멤버에는 암시적으로 '{1}' 형식이 포함됩니다.", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' 모듈에 대한 해결을 '{1}' 위치의 캐시에서 찾았습니다.", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "'{1}' 위치의 캐시에서 형식 참조 지시어 '{0}'에 대한 해상도가 발견되었습니다.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "문자열 값 속성 이름에 대해서만 'keyof'를 확인합니다(숫자나 기호 아님).", + "Resolving_in_0_mode_with_conditions_1_6402": "조건이 {1}인 {0} 모드에서 확인하는 중입니다.", "Resolving_module_0_from_1_6086": "======== '{1}'에서 '{0}' 모듈을 확인하는 중입니다. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "기본 URL '{1}' - '{2}'을(를) 기준으로 모듈 이름 '{0}'을(를) 확인하는 중입니다.", "Resolving_real_path_for_0_result_1_6130": "'{0}'의 실제 경로를 확인하는 중입니다. 결과: '{1}'.", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "컴파일을 위해 지정된 루트 파일", "STRATEGY_6039": "전략", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "프로젝트의 증분 컴파일을 허용하도록 .tsbuildinfo 파일을 저장합니다.", + "Saw_non_matching_condition_0_6405": "비일치 조건 '{0}'을(를) 확인했습니다.", "Scoped_package_detected_looking_in_0_6182": "범위가 지정된 패키지가 검색되었습니다. '{0}'에서 찾습니다.", "Selection_is_not_a_valid_statement_or_statements_95155": "선택 항목이 유효한 하나의 문 또는 여러 문이 아닙니다.", "Selection_is_not_a_valid_type_node_95133": "선택 영역이 유효한 형식 노드가 아닙니다.", @@ -1474,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "이 JSX 태그의 '{0}' 속성에는 '{1}' 형식의 자식 하나가 필요하지만, 여러 자식이 제공되었습니다.", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "이 JSX 태그의 '{0}' 속성에는 여러 자식이 있어야 하는 '{1}' 형식이 필요하지만, 단일 자식만 제공되었습니다.", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "'{0}'이(가) '{1}'과(와) 겹치지 않으므로 이 비교는 의도하지 않은 것 같습니다.", + "This_condition_will_always_return_0_2845": "이 조건은 항상 '{0}'을(를) 반환합니다.", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "JavaScript는 값이 아닌 참조로 개체를 비교하므로 이 조건은 항상 '{0}'을(를) 반환합니다.", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "이 '{0}'(은)는 항상 정의되어 있으므로 이 조건은 항상 true를 반환합니다.", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "함수가 항상 정의되므로 이 조건은 항상 true를 반환합니다. 대신 호출하시겠어요?", @@ -1648,9 +1654,12 @@ "Updating_output_of_project_0_6373": "'{0}' 프로젝트의 출력을 업데이트하는 중...", "Updating_output_timestamps_of_project_0_6359": "'{0}' 프로젝트의 출력 타임스탬프를 업데이트하는 중...", "Updating_unchanged_output_timestamps_of_project_0_6371": "'{0}' 프로젝트의 변경되지 않은 출력 타임스탬프를 업데이트하는 중...", + "Use_0_95174": "`{0}`을(를) 사용합니다.", + "Use_Number_isNaN_in_all_conditions_95175": "모든 조건에서 'Number.isNaN'을 사용합니다.", "Use_element_access_for_0_95145": "'{0}'에 요소 액세스 사용", "Use_element_access_for_all_undeclared_properties_95146": "선언되지 않은 모든 속성에 요소 액세스를 사용합니다.", "Use_synthetic_default_member_95016": "가상 '기본' 멤버를 사용합니다.", + "Using_0_subpath_1_with_target_2_6404": "'{0}' 하위 경로 '{1}'과(와) 대상 '{2}'을(를) 사용하는 중입니다.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "ECMAScript 5 이상에서만 'for...of' 문에서 문자열을 사용할 수 있습니다.", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "--build를 사용하면 -b가 tsc로 하여금 컴파일러보다 빌드 오케스트레이터처럼 작동하도록 합니다. 이 항목은 {0}에서 더 자세히 알아볼 수 있는 복합 프로젝트를 구축하는 데 사용됩니다.", "Using_compiler_options_of_project_reference_redirect_0_6215": "프로젝트 참조 리디렉션 '{0}'의 컴파일러 옵션을 사용 중입니다.", diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 6db4e11aa5970..753f7673d8924 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -137,11 +137,13 @@ interface AudioWorkletNodeOptions extends AudioNodeOptions { interface AuthenticationExtensionsClientInputs { appid?: string; credProps?: boolean; + hmacCreateSecret?: boolean; } interface AuthenticationExtensionsClientOutputs { appid?: boolean; credProps?: CredentialPropertiesOutput; + hmacCreateSecret?: boolean; } interface AuthenticatorSelectionCriteria { @@ -1344,6 +1346,7 @@ interface RTCInboundRtpStreamStats extends RTCReceivedRtpStreamStats { frameHeight?: number; frameWidth?: number; framesDecoded?: number; + framesDropped?: number; framesPerSecond?: number; framesReceived?: number; headerBytesReceived?: number; @@ -1363,6 +1366,7 @@ interface RTCInboundRtpStreamStats extends RTCReceivedRtpStreamStats { totalAudioEnergy?: number; totalDecodeTime?: number; totalInterFrameDelay?: number; + totalProcessingDelay?: number; totalSamplesDuration?: number; totalSamplesReceived?: number; totalSquaredInterFrameDelay?: number; @@ -1421,7 +1425,6 @@ interface RTCPeerConnectionIceEventInit extends EventInit { } interface RTCReceivedRtpStreamStats extends RTCRtpStreamStats { - framesDropped?: number; jitter?: number; packetsLost?: number; packetsReceived?: number; @@ -1466,6 +1469,8 @@ interface RTCRtpContributingSource { interface RTCRtpEncodingParameters extends RTCRtpCodingParameters { active?: boolean; maxBitrate?: number; + maxFramerate?: number; + networkPriority?: RTCPriorityType; priority?: RTCPriorityType; scaleResolutionDownBy?: number; } @@ -1886,10 +1891,10 @@ interface ValidityStateFlags { } interface VideoColorSpaceInit { - fullRange?: boolean; - matrix?: VideoMatrixCoefficients; - primaries?: VideoColorPrimaries; - transfer?: VideoTransferCharacteristics; + fullRange?: boolean | null; + matrix?: VideoMatrixCoefficients | null; + primaries?: VideoColorPrimaries | null; + transfer?: VideoTransferCharacteristics | null; } interface VideoConfiguration { @@ -1904,7 +1909,7 @@ interface VideoConfiguration { width: number; } -interface VideoFrameMetadata { +interface VideoFrameCallbackMetadata { captureTime?: DOMHighResTimeStamp; expectedDisplayTime: DOMHighResTimeStamp; height: number; @@ -2066,7 +2071,7 @@ interface AbortSignal extends EventTarget { declare var AbortSignal: { prototype: AbortSignal; new(): AbortSignal; - // abort(): AbortSignal; - To be re-added in the future + abort(reason?: any): AbortSignal; timeout(milliseconds: number): AbortSignal; }; @@ -2202,7 +2207,7 @@ declare var AnimationPlaybackEvent: { }; interface AnimationTimeline { - readonly currentTime: number | null; + readonly currentTime: CSSNumberish | null; } declare var AnimationTimeline: { @@ -2455,6 +2460,8 @@ declare var AuthenticatorAssertionResponse: { interface AuthenticatorAttestationResponse extends AuthenticatorResponse { readonly attestationObject: ArrayBuffer; getAuthenticatorData(): ArrayBuffer; + getPublicKey(): ArrayBuffer | null; + getPublicKeyAlgorithm(): COSEAlgorithmIdentifier; getTransports(): string[]; } @@ -2654,6 +2661,14 @@ declare var CSSConditionRule: { new(): CSSConditionRule; }; +interface CSSContainerRule extends CSSConditionRule { +} + +declare var CSSContainerRule: { + prototype: CSSContainerRule; + new(): CSSContainerRule; +}; + interface CSSCounterStyleRule extends CSSRule { additiveSymbols: string; fallback: string; @@ -2963,6 +2978,9 @@ interface CSSStyleDeclaration { columnWidth: string; columns: string; contain: string; + container: string; + containerName: string; + containerType: string; content: string; counterIncrement: string; counterReset: string; @@ -3031,6 +3049,7 @@ interface CSSStyleDeclaration { gridTemplateColumns: string; gridTemplateRows: string; height: string; + hyphenateCharacter: string; hyphens: string; /** @deprecated */ imageOrientation: string; @@ -3107,6 +3126,7 @@ interface CSSStyleDeclaration { outlineWidth: string; overflow: string; overflowAnchor: string; + overflowClipMargin: string; overflowWrap: string; overflowX: string; overflowY: string; @@ -3564,6 +3584,7 @@ interface CanvasPath { moveTo(x: number, y: number): void; quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; rect(x: number, y: number, w: number, h: number): void; + roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | (number | DOMPointInit)[]): void; } interface CanvasPathDrawingStyles { @@ -4970,6 +4991,17 @@ interface EXT_texture_filter_anisotropic { readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum; } +interface EXT_texture_norm16 { + readonly R16_EXT: GLenum; + readonly R16_SNORM_EXT: GLenum; + readonly RG16_EXT: GLenum; + readonly RG16_SNORM_EXT: GLenum; + readonly RGB16_EXT: GLenum; + readonly RGB16_SNORM_EXT: GLenum; + readonly RGBA16_EXT: GLenum; + readonly RGBA16_SNORM_EXT: GLenum; +} + interface ElementEventMap { "fullscreenchange": Event; "fullscreenerror": Event; @@ -6310,6 +6342,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, quality?: any): string; + transferControlToOffscreen(): OffscreenCanvas; addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -9024,7 +9057,7 @@ declare var ImageBitmap: { interface ImageBitmapRenderingContext { /** Returns the canvas element that the context is bound to. */ - readonly canvas: HTMLCanvasElement; + readonly canvas: HTMLCanvasElement | OffscreenCanvas; /** Transfers the underlying bitmap data from imageBitmap to context, and the bitmap becomes the contents of the canvas element to which context is bound. */ transferFromImageBitmap(bitmap: ImageBitmap | null): void; } @@ -9055,6 +9088,7 @@ interface InnerHTML { innerHTML: string; } +/** Available only in secure contexts. */ interface InputDeviceInfo extends MediaDeviceInfo { } @@ -10259,6 +10293,16 @@ declare var Notification: { requestPermission(deprecatedCallback?: NotificationPermissionCallback): Promise; }; +interface OES_draw_buffers_indexed { + blendEquationSeparateiOES(buf: GLuint, modeRGB: GLenum, modeAlpha: GLenum): void; + blendEquationiOES(buf: GLuint, mode: GLenum): void; + blendFuncSeparateiOES(buf: GLuint, srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum): void; + blendFunciOES(buf: GLuint, src: GLenum, dst: GLenum): void; + colorMaskiOES(buf: GLuint, r: GLboolean, g: GLboolean, b: GLboolean, a: GLboolean): void; + disableiOES(target: GLenum, index: GLuint): void; + enableiOES(target: GLenum, index: GLuint): void; +} + /** The OES_element_index_uint extension is part of the WebGL API and adds support for gl.UNSIGNED_INT types to WebGLRenderingContext.drawElements(). */ interface OES_element_index_uint { } @@ -10337,6 +10381,57 @@ declare var OfflineAudioContext: { new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; }; +interface OffscreenCanvasEventMap { + "contextlost": Event; + "contextrestored": Event; +} + +interface OffscreenCanvas extends EventTarget { + /** + * These attributes return the dimensions of the OffscreenCanvas object's bitmap. + * + * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). + */ + height: number; + oncontextlost: ((this: OffscreenCanvas, ev: Event) => any) | null; + oncontextrestored: ((this: OffscreenCanvas, ev: Event) => any) | null; + /** + * These attributes return the dimensions of the OffscreenCanvas object's bitmap. + * + * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). + */ + width: number; + /** + * Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API. + * + * This specification defines the "2d" context below, which is similar but distinct from the "2d" context that is created from a canvas element. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL] + * + * Returns null if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context). + */ + getContext(contextId: OffscreenRenderingContextId, options?: any): OffscreenRenderingContext | null; + /** Returns a newly created ImageBitmap object with the image in the OffscreenCanvas object. The image in the OffscreenCanvas object is replaced with a new blank image. */ + transferToImageBitmap(): ImageBitmap; + addEventListener(type: K, listener: (this: OffscreenCanvas, ev: OffscreenCanvasEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OffscreenCanvas, ev: OffscreenCanvasEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var OffscreenCanvas: { + prototype: OffscreenCanvas; + new(width: number, height: number): OffscreenCanvas; +}; + +interface OffscreenCanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform { + readonly canvas: OffscreenCanvas; + commit(): void; +} + +declare var OffscreenCanvasRenderingContext2D: { + prototype: OffscreenCanvasRenderingContext2D; + new(): OffscreenCanvasRenderingContext2D; +}; + /** The OscillatorNode interface represents a periodic waveform, such as a sine wave. It is an AudioScheduledSourceNode audio-processing module that causes a specified frequency of a given wave to be created—in effect, a constant tone. */ interface OscillatorNode extends AudioScheduledSourceNode { readonly detune: AudioParam; @@ -16047,7 +16142,7 @@ declare var WebGLRenderingContext: { }; interface WebGLRenderingContextBase { - readonly canvas: HTMLCanvasElement; + readonly canvas: HTMLCanvasElement | OffscreenCanvas; readonly drawingBufferHeight: GLsizei; readonly drawingBufferWidth: GLsizei; activeTexture(texture: GLenum): void; @@ -17525,7 +17620,7 @@ interface UnderlyingSourceStartCallback { } interface VideoFrameRequestCallback { - (now: DOMHighResTimeStamp, metadata: VideoFrameMetadata): void; + (now: DOMHighResTimeStamp, metadata: VideoFrameCallbackMetadata): void; } interface VoidFunction { @@ -18202,7 +18297,7 @@ type BodyInit = ReadableStream | XMLHttpRequestBodyInit; type BufferSource = ArrayBufferView | ArrayBuffer; type COSEAlgorithmIdentifier = number; type CSSNumberish = number; -type CanvasImageSource = HTMLOrSVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap; +type CanvasImageSource = HTMLOrSVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas; type ClipboardItemData = Promise; type ClipboardItems = ClipboardItem[]; type ConstrainBoolean = boolean | ConstrainBooleanParameters; @@ -18239,6 +18334,7 @@ type MediaProvider = MediaStream | MediaSource | Blob; type MessageEventSource = WindowProxy | MessagePort | ServiceWorker; type MutationRecordType = "attributes" | "characterData" | "childList"; type NamedCurve = string; +type OffscreenRenderingContext = OffscreenCanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext; type OnBeforeUnloadEventHandler = OnBeforeUnloadEventHandlerNonNull | null; type OnErrorEventHandler = OnErrorEventHandlerNonNull | null; type PerformanceEntryList = PerformanceEntry[]; @@ -18247,9 +18343,9 @@ type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableSt type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; type RenderingContext = CanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext; type RequestInfo = Request | string; -type TexImageSource = ImageBitmap | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; +type TexImageSource = ImageBitmap | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | OffscreenCanvas; type TimerHandler = string | Function; -type Transferable = ImageBitmap | MessagePort | ReadableStream | WritableStream | TransformStream | ArrayBuffer; +type Transferable = OffscreenCanvas | ImageBitmap | MessagePort | ReadableStream | WritableStream | TransformStream | ArrayBuffer; type Uint32List = Uint32Array | GLuint[]; type VibratePattern = number | number[]; type WindowProxy = Window; @@ -18329,6 +18425,7 @@ type MediaStreamTrackState = "ended" | "live"; type NavigationTimingType = "back_forward" | "navigate" | "prerender" | "reload"; type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationPermission = "default" | "denied" | "granted"; +type OffscreenRenderingContextId = "2d" | "bitmaprenderer" | "webgl" | "webgl2" | "webgpu"; type OrientationLockType = "any" | "landscape" | "landscape-primary" | "landscape-secondary" | "natural" | "portrait" | "portrait-primary" | "portrait-secondary"; type OrientationType = "landscape-primary" | "landscape-secondary" | "portrait-primary" | "portrait-secondary"; type OscillatorType = "custom" | "sawtooth" | "sine" | "square" | "triangle"; diff --git a/lib/lib.dom.iterable.d.ts b/lib/lib.dom.iterable.d.ts index cde428dfcb3cf..9cd574ca52d97 100644 --- a/lib/lib.dom.iterable.d.ts +++ b/lib/lib.dom.iterable.d.ts @@ -46,6 +46,10 @@ interface Cache { addAll(requests: Iterable): Promise; } +interface CanvasPath { + roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | Iterable): void; +} + interface CanvasPathDrawingStyles { setLineDash(segments: Iterable): void; } @@ -273,8 +277,8 @@ interface WEBGL_draw_buffers { interface WEBGL_multi_draw { multiDrawArraysInstancedWEBGL(mode: GLenum, firstsList: Int32Array | Iterable, firstsOffset: GLuint, countsList: Int32Array | Iterable, countsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; multiDrawArraysWEBGL(mode: GLenum, firstsList: Int32Array | Iterable, firstsOffset: GLuint, countsList: Int32Array | Iterable, countsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, drawcount: GLsizei): void; } interface WebGL2RenderingContextBase { diff --git a/lib/lib.es2015.symbol.wellknown.d.ts b/lib/lib.es2015.symbol.wellknown.d.ts index b1e3264368821..81e052bf26d27 100644 --- a/lib/lib.es2015.symbol.wellknown.d.ts +++ b/lib/lib.es2015.symbol.wellknown.d.ts @@ -239,9 +239,9 @@ interface String { match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null; /** - * Replaces first match with string or all matches with RegExp. - * @param searchValue A string or RegExp search value. - * @param replaceValue A string containing the text to replace for match. + * Passes a string and {@linkcode replaceValue} to the `[Symbol.replace]` method on {@linkcode searchValue}. This method is expected to implement its own replacement algorithm. + * @param searchValue An object that supports searching for and replacing matches within a string. + * @param replaceValue The replacement text. */ replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string; diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 62cb9fb3814d9..01610d97fb3ce 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -443,8 +443,8 @@ interface String { /** * Replaces text in a string, using a regular expression or search string. - * @param searchValue A string to search for. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + * @param searchValue A string or regular expression to search for. + * @param replaceValue A string containing the text to replace. When the {@linkcode searchValue} is a `RegExp`, all matches are replaced if the `g` flag is set (or only those matches at the beginning, if the `y` flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced. */ replace(searchValue: string | RegExp, replaceValue: string): string; @@ -931,6 +931,7 @@ interface DateConstructor { * @param ms A number from 0 to 999 that specifies the milliseconds. */ UTC(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + /** Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC). */ now(): number; } diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index f6ab7e9363d4b..209f41cfdbddf 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -699,10 +699,10 @@ interface UnderlyingSource { } interface VideoColorSpaceInit { - fullRange?: boolean; - matrix?: VideoMatrixCoefficients; - primaries?: VideoColorPrimaries; - transfer?: VideoTransferCharacteristics; + fullRange?: boolean | null; + matrix?: VideoMatrixCoefficients | null; + primaries?: VideoColorPrimaries | null; + transfer?: VideoTransferCharacteristics | null; } interface VideoConfiguration { @@ -752,7 +752,7 @@ interface AbortController { /** Returns the AbortSignal object associated with this object. */ readonly signal: AbortSignal; /** Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. */ - // abort(): AbortSignal; - To be re-added in the future + abort(reason?: any): void; } declare var AbortController: { @@ -898,6 +898,44 @@ declare var CacheStorage: { new(): CacheStorage; }; +interface CanvasCompositing { + globalAlpha: number; + globalCompositeOperation: GlobalCompositeOperation; +} + +interface CanvasDrawImage { + drawImage(image: CanvasImageSource, dx: number, dy: number): void; + drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void; + drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void; +} + +interface CanvasDrawPath { + beginPath(): void; + clip(fillRule?: CanvasFillRule): void; + clip(path: Path2D, fillRule?: CanvasFillRule): void; + fill(fillRule?: CanvasFillRule): void; + fill(path: Path2D, fillRule?: CanvasFillRule): void; + isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean; + isPointInStroke(x: number, y: number): boolean; + isPointInStroke(path: Path2D, x: number, y: number): boolean; + stroke(): void; + stroke(path: Path2D): void; +} + +interface CanvasFillStrokeStyles { + fillStyle: string | CanvasGradient | CanvasPattern; + strokeStyle: string | CanvasGradient | CanvasPattern; + createConicGradient(startAngle: number, x: number, y: number): CanvasGradient; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; + createPattern(image: CanvasImageSource, repetition: string | null): CanvasPattern | null; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; +} + +interface CanvasFilters { + filter: string; +} + /** An opaque object describing a gradient. It is returned by the methods CanvasRenderingContext2D.createLinearGradient() or CanvasRenderingContext2D.createRadialGradient(). */ interface CanvasGradient { /** @@ -913,6 +951,19 @@ declare var CanvasGradient: { new(): CanvasGradient; }; +interface CanvasImageData { + createImageData(sw: number, sh: number, settings?: ImageDataSettings): ImageData; + createImageData(imagedata: ImageData): ImageData; + getImageData(sx: number, sy: number, sw: number, sh: number, settings?: ImageDataSettings): ImageData; + putImageData(imagedata: ImageData, dx: number, dy: number): void; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void; +} + +interface CanvasImageSmoothing { + imageSmoothingEnabled: boolean; + imageSmoothingQuality: ImageSmoothingQuality; +} + interface CanvasPath { arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void; arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; @@ -923,6 +974,17 @@ interface CanvasPath { moveTo(x: number, y: number): void; quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; rect(x: number, y: number, w: number, h: number): void; + roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | (number | DOMPointInit)[]): void; +} + +interface CanvasPathDrawingStyles { + lineCap: CanvasLineCap; + lineDashOffset: number; + lineJoin: CanvasLineJoin; + lineWidth: number; + miterLimit: number; + getLineDash(): number[]; + setLineDash(segments: number[]): void; } /** An opaque object describing a pattern, based on an image, a canvas, or a video, created by the CanvasRenderingContext2D.createPattern() method. */ @@ -936,6 +998,49 @@ declare var CanvasPattern: { new(): CanvasPattern; }; +interface CanvasRect { + clearRect(x: number, y: number, w: number, h: number): void; + fillRect(x: number, y: number, w: number, h: number): void; + strokeRect(x: number, y: number, w: number, h: number): void; +} + +interface CanvasShadowStyles { + shadowBlur: number; + shadowColor: string; + shadowOffsetX: number; + shadowOffsetY: number; +} + +interface CanvasState { + restore(): void; + save(): void; +} + +interface CanvasText { + fillText(text: string, x: number, y: number, maxWidth?: number): void; + measureText(text: string): TextMetrics; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; +} + +interface CanvasTextDrawingStyles { + direction: CanvasDirection; + font: string; + fontKerning: CanvasFontKerning; + textAlign: CanvasTextAlign; + textBaseline: CanvasTextBaseline; +} + +interface CanvasTransform { + getTransform(): DOMMatrix; + resetTransform(): void; + rotate(angle: number): void; + scale(x: number, y: number): void; + setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void; + setTransform(transform?: DOMMatrix2DInit): void; + transform(a: number, b: number, c: number, d: number, e: number, f: number): void; + translate(x: number, y: number): void; +} + /** The Client interface represents an executable context such as a Worker, or a SharedWorker. Window clients are represented by the more-specific WindowClient. You can get Client/WindowClient objects from methods such as Clients.matchAll() and Clients.get(). */ interface Client { readonly frameType: FrameType; @@ -1362,6 +1467,17 @@ interface EXT_texture_filter_anisotropic { readonly TEXTURE_MAX_ANISOTROPY_EXT: GLenum; } +interface EXT_texture_norm16 { + readonly R16_EXT: GLenum; + readonly R16_SNORM_EXT: GLenum; + readonly RG16_EXT: GLenum; + readonly RG16_SNORM_EXT: GLenum; + readonly RGB16_EXT: GLenum; + readonly RGB16_SNORM_EXT: GLenum; + readonly RGBA16_EXT: GLenum; + readonly RGBA16_SNORM_EXT: GLenum; +} + /** Events providing information related to errors in scripts or in files. */ interface ErrorEvent extends Event { readonly colno: number; @@ -2396,6 +2512,16 @@ declare var NotificationEvent: { new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; }; +interface OES_draw_buffers_indexed { + blendEquationSeparateiOES(buf: GLuint, modeRGB: GLenum, modeAlpha: GLenum): void; + blendEquationiOES(buf: GLuint, mode: GLenum): void; + blendFuncSeparateiOES(buf: GLuint, srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum): void; + blendFunciOES(buf: GLuint, src: GLenum, dst: GLenum): void; + colorMaskiOES(buf: GLuint, r: GLboolean, g: GLboolean, b: GLboolean, a: GLboolean): void; + disableiOES(target: GLenum, index: GLuint): void; + enableiOES(target: GLenum, index: GLuint): void; +} + /** The OES_element_index_uint extension is part of the WebGL API and adds support for gl.UNSIGNED_INT types to WebGLRenderingContext.drawElements(). */ interface OES_element_index_uint { } @@ -2441,10 +2567,57 @@ interface OVR_multiview2 { readonly MAX_VIEWS_OVR: GLenum; } -/** @deprecated this is not available in most browsers */ +interface OffscreenCanvasEventMap { + "contextlost": Event; + "contextrestored": Event; +} + interface OffscreenCanvas extends EventTarget { + /** + * These attributes return the dimensions of the OffscreenCanvas object's bitmap. + * + * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). + */ + height: number; + oncontextlost: ((this: OffscreenCanvas, ev: Event) => any) | null; + oncontextrestored: ((this: OffscreenCanvas, ev: Event) => any) | null; + /** + * These attributes return the dimensions of the OffscreenCanvas object's bitmap. + * + * They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). + */ + width: number; + /** + * Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API. + * + * This specification defines the "2d" context below, which is similar but distinct from the "2d" context that is created from a canvas element. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL] + * + * Returns null if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context). + */ + getContext(contextId: OffscreenRenderingContextId, options?: any): OffscreenRenderingContext | null; + /** Returns a newly created ImageBitmap object with the image in the OffscreenCanvas object. The image in the OffscreenCanvas object is replaced with a new blank image. */ + transferToImageBitmap(): ImageBitmap; + addEventListener(type: K, listener: (this: OffscreenCanvas, ev: OffscreenCanvasEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: OffscreenCanvas, ev: OffscreenCanvasEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } +declare var OffscreenCanvas: { + prototype: OffscreenCanvas; + new(width: number, height: number): OffscreenCanvas; +}; + +interface OffscreenCanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform { + readonly canvas: OffscreenCanvas; + commit(): void; +} + +declare var OffscreenCanvasRenderingContext2D: { + prototype: OffscreenCanvasRenderingContext2D; + new(): OffscreenCanvasRenderingContext2D; +}; + /** This Canvas 2D API interface is used to declare a path that can then be used on a CanvasRenderingContext2D object. The path methods of the CanvasRenderingContext2D interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired. */ interface Path2D extends CanvasPath { /** Adds to the path the path given by the argument. */ @@ -5940,6 +6113,7 @@ type ImageBitmapSource = CanvasImageSource | Blob | ImageData; type Int32List = Int32Array | GLint[]; type MessageEventSource = MessagePort | ServiceWorker; type NamedCurve = string; +type OffscreenRenderingContext = OffscreenCanvasRenderingContext2D | ImageBitmapRenderingContext | WebGLRenderingContext | WebGL2RenderingContext; type OnErrorEventHandler = OnErrorEventHandlerNonNull | null; type PerformanceEntryList = PerformanceEntry[]; type PushMessageDataInit = BufferSource | string; @@ -5954,6 +6128,16 @@ type Uint32List = Uint32Array | GLuint[]; type VibratePattern = number | number[]; type XMLHttpRequestBodyInit = Blob | BufferSource | FormData | URLSearchParams | string; type BinaryType = "arraybuffer" | "blob"; +type CanvasDirection = "inherit" | "ltr" | "rtl"; +type CanvasFillRule = "evenodd" | "nonzero"; +type CanvasFontKerning = "auto" | "none" | "normal"; +type CanvasFontStretch = "condensed" | "expanded" | "extra-condensed" | "extra-expanded" | "normal" | "semi-condensed" | "semi-expanded" | "ultra-condensed" | "ultra-expanded"; +type CanvasFontVariantCaps = "all-petite-caps" | "all-small-caps" | "normal" | "petite-caps" | "small-caps" | "titling-caps" | "unicase"; +type CanvasLineCap = "butt" | "round" | "square"; +type CanvasLineJoin = "bevel" | "miter" | "round"; +type CanvasTextAlign = "center" | "end" | "left" | "right" | "start"; +type CanvasTextBaseline = "alphabetic" | "bottom" | "hanging" | "ideographic" | "middle" | "top"; +type CanvasTextRendering = "auto" | "geometricPrecision" | "optimizeLegibility" | "optimizeSpeed"; type ClientTypes = "all" | "sharedworker" | "window" | "worker"; type ColorGamut = "p3" | "rec2020" | "srgb"; type ColorSpaceConversion = "default" | "none"; @@ -5963,12 +6147,14 @@ type FileSystemHandleKind = "directory" | "file"; type FontFaceLoadStatus = "error" | "loaded" | "loading" | "unloaded"; type FontFaceSetLoadStatus = "loaded" | "loading"; type FrameType = "auxiliary" | "nested" | "none" | "top-level"; +type GlobalCompositeOperation = "color" | "color-burn" | "color-dodge" | "copy" | "darken" | "destination-atop" | "destination-in" | "destination-out" | "destination-over" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "lighter" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light" | "source-atop" | "source-in" | "source-out" | "source-over" | "xor"; type HdrMetadataType = "smpteSt2086" | "smpteSt2094-10" | "smpteSt2094-40"; type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique"; type IDBRequestReadyState = "done" | "pending"; type IDBTransactionDurability = "default" | "relaxed" | "strict"; type IDBTransactionMode = "readonly" | "readwrite" | "versionchange"; type ImageOrientation = "flipY" | "none"; +type ImageSmoothingQuality = "high" | "low" | "medium"; type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; type KeyType = "private" | "public" | "secret"; type KeyUsage = "decrypt" | "deriveBits" | "deriveKey" | "encrypt" | "sign" | "unwrapKey" | "verify" | "wrapKey"; @@ -5977,6 +6163,7 @@ type MediaDecodingType = "file" | "media-source" | "webrtc"; type MediaEncodingType = "record" | "webrtc"; type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationPermission = "default" | "denied" | "granted"; +type OffscreenRenderingContextId = "2d" | "bitmaprenderer" | "webgl" | "webgl2" | "webgpu"; type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "xr-spatial-tracking"; type PermissionState = "denied" | "granted" | "prompt"; type PredefinedColorSpace = "display-p3" | "srgb"; diff --git a/lib/lib.webworker.iterable.d.ts b/lib/lib.webworker.iterable.d.ts index 3d9e75d003cb0..b8035985329ab 100644 --- a/lib/lib.webworker.iterable.d.ts +++ b/lib/lib.webworker.iterable.d.ts @@ -26,6 +26,14 @@ interface Cache { addAll(requests: Iterable): Promise; } +interface CanvasPath { + roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | Iterable): void; +} + +interface CanvasPathDrawingStyles { + setLineDash(segments: Iterable): void; +} + interface DOMStringList { [Symbol.iterator](): IterableIterator; } @@ -103,8 +111,8 @@ interface WEBGL_draw_buffers { interface WEBGL_multi_draw { multiDrawArraysInstancedWEBGL(mode: GLenum, firstsList: Int32Array | Iterable, firstsOffset: GLuint, countsList: Int32Array | Iterable, countsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; multiDrawArraysWEBGL(mode: GLenum, firstsList: Int32Array | Iterable, firstsOffset: GLuint, countsList: Int32Array | Iterable, countsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; - multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, instanceCountsList: Int32Array | Iterable, instanceCountsOffset: GLuint, drawcount: GLsizei): void; + multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | Iterable, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable, offsetsOffset: GLuint, drawcount: GLsizei): void; } interface WebGL2RenderingContextBase { diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index 107a9859cd27d..fc734cc2d1663 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Obsługa eksperymentalna dekoratorów to funkcja, która może ulec zmianie w nowszych wersjach. Ustaw opcję „experimentalDecorators” w pliku „tsconfig” lub „jsconfig”, aby usunąć to ostrzeżenie.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Jawnie określony rodzaj rozpoznawania modułów: „{0}”.", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Nie można wykonać potęgowania wartości typu „bigint”, chyba że opcja „target” ma wartość „es2016” lub nowszą.", + "Export_0_from_module_1_90059": "Eksportuj „{0}” z modułu „{1}”", + "Export_all_referenced_locals_90060": "Eksportuj wszystkie przywoływane zmienne lokalne", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Nie można użyć przypisania eksportu, gdy są używane moduły języka ECMAScript. Zamiast tego rozważ użycie elementu „export default” lub innego formatu modułu.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Przypisanie eksportu nie jest obsługiwane, gdy flaga „--module” ma postać „system”.", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Deklaracja eksportu powoduje konflikt z wyeksportowaną deklaracją „{0}”.", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Określ, że element keyof ma zwracać tylko ciągi zamiast ciągów, liczb i symboli. Starsza opcja.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Ustaw wywołanie „super()” jako pierwszą instrukcję w konstruktorze", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Zmapowany typ obiektu niejawnie ma typ szablonu „any”.", + "Matched_0_condition_1_6403": "Dopasowano „{0}” warunku „{1}”.", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Dopasowywane domyślnie do wzorca dołączania „**/*”", "Matched_by_include_pattern_0_in_1_1407": "Zgodne z wzorcem dołączania „{0}” w elemencie „{1}”", "Member_0_implicitly_has_an_1_type_7008": "Dla składowej „{0}” niejawnie określono typ „{1}”.", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Znaleziono rozwiązanie dla modułu „{0}” w pamięci podręcznej z lokalizacji „{1}”.", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "Znaleziono rozwiązanie dla dyrektywy odwołania do typu „{0}” w pamięci podręcznej z lokalizacji „{1}”.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Rozwiązuj elementy „keyof” tylko do nazw właściwości mających jako wartość ciągi (nie liczby czy symbole).", + "Resolving_in_0_mode_with_conditions_1_6402": "Rozpoznawanie w trybie {0} z warunkami {1}.", "Resolving_module_0_from_1_6086": "======== Rozpoznawanie modułu „{0}” na podstawie „{1}”. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Rozpoznawanie nazwy modułu „{0}” względem podstawowego adresu URL „{1}” — „{2}”.", "Resolving_real_path_for_0_result_1_6130": "Rozpoznawanie rzeczywistej ścieżki elementu ƒ„{0}”, wynik: „{1}”.", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "Plik główny określony na potrzeby kompilacji", "STRATEGY_6039": "STRATEGIA", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Zapisuj pliki tsbuildinfo, aby umożliwić przyrostową kompilację projektów.", + "Saw_non_matching_condition_0_6405": "Wyświetlono niezgodny warunek „{0}”.", "Scoped_package_detected_looking_in_0_6182": "Wykryto pakiet w zakresie, wyszukiwanie w „{0}”", "Selection_is_not_a_valid_statement_or_statements_95155": "Wybór nie jest prawidłową instrukcją ani instrukcjami", "Selection_is_not_a_valid_type_node_95133": "Wybór nie jest prawidłowym węzłem typu", @@ -1427,7 +1432,6 @@ "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "Lewa strona operacji arytmetycznej musi być typu „any”, „number”, „bigint” lub typu wyliczeniowego.", "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "Lewa strona wyrażenia przypisania nie może być opcjonalnym dostępem do właściwości.", "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "Lewa strona wyrażenia przypisania musi być zmienną lub dostępem do właściwości.", - "The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or__2360": "Lewa strona wyrażenia „in” musi być identyfikatorem prywatnym lub typem „any”, „string”, „number” lub „symbol”.", "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "Lewa strona wyrażenia „instanceof” musi być typu „any”, typu obiektu lub parametrem typu.", "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "Ustawienia regionalne używane przy wyświetlaniu komunikatów użytkownikowi (np. „pl-pl”)", "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "Maksymalna głębokość zależności na potrzeby wyszukiwania w elemencie node_modules i ładownia plików JavaScript.", @@ -1448,7 +1452,6 @@ "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "Zwracany typ funkcji lub metody asynchronicznej musi być globalnym typem Promise. Czy chodziło Ci o typ „Promise<{0}>”?", "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "Prawa strona instrukcji „for...in” musi zawierać typ „any”, typ obiektu lub parametr typu, a tutaj ma typ „{0}”.", "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "Prawa strona operacji arytmetycznej musi być typu „any”, „number”, „bigint” lub typu wyliczeniowego.", - "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361": "Typ pierwotny nie może znajdować się po prawej stronie wyrażenia „in”.", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "Prawa strona wyrażenia „instanceof” musi być typu „any” lub typu, który można przypisać do typu interfejsu „Function”.", "The_root_value_of_a_0_file_must_be_an_object_5092": "Wartość katalogu głównego pliku „{0}” musi być obiektem.", "The_shadowing_declaration_of_0_is_defined_here_18017": "Deklaracja przesłaniania „{0}” jest zdefiniowana tutaj", @@ -1476,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "Element prop „{0}” tego tagu JSX oczekuje pojedynczego elementu podrzędnego typu „{1}”, ale podano wiele elementów podrzędnych.", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "Element prop „{0}” tego tagu JSX oczekuje typu „{1}”, który wymaga wielu elementów podrzędnych, ale podano tylko jeden element podrzędny.", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "To porównanie wydaje się niezamierzone, ponieważ typy „{0}” i „{1}” nie nakładają się na siebie.", + "This_condition_will_always_return_0_2845": "Ten warunek będzie zawsze zwracać wartość „{0}”.", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Ten warunek zawsze będzie zwracać wartość „{0}”, ponieważ język JavaScript porównuje obiekty według odwołania, a nie wartości.", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Ten warunek będzie zawsze zwracać wartość true, ponieważ wartość '{0}' jest zawsze prawdziwa.", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Ten warunek będzie zawsze zwracał wartość true, ponieważ funkcja jest zawsze zdefiniowana. Czy chcesz wywołać ją zamiast tego?", @@ -1551,6 +1555,7 @@ "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "Nie można przypisać typu \"{0}\" do typu \"{1}\" o wartości \"exactOptionalPropertyTypes: true\". Rozważ dodanie elementu \"undefined\" do typu elementu docelowego.", "Type_0_is_not_comparable_to_type_1_2678": "Typu „{0}” nie można porównać z typem „{1}”.", "Type_0_is_not_generic_2315": "Typ „{0}” nie jest ogólny.", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "Typ „{0}” może reprezentować wartość pierwotną, co nie jest dozwolone jako prawy operand operatora „in”.", "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "Typ „{0}” musi zawierać metodę „[Symbol.asyncIterator]()” zwracającą iterator asynchroniczny.", "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "Typ „{0}” musi zawierać metodę „[Symbol.iterator]()” zwracającą iterator.", "Type_0_provides_no_match_for_the_signature_1_2658": "Typ „{0}” nie udostępnia dopasowania dla sygnatury „{1}”.", @@ -1649,9 +1654,12 @@ "Updating_output_of_project_0_6373": "Trwa aktualizowanie danych wyjściowych projektu „{0}”...", "Updating_output_timestamps_of_project_0_6359": "Trwa aktualizowanie sygnatury czasowej danych wyjściowych projektu „{0}”...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Trwa aktualizowanie niezmienionych sygnatur czasowych danych wyjściowych projektu „{0}”...", + "Use_0_95174": "Użyj „{0}”.", + "Use_Number_isNaN_in_all_conditions_95175": "Użyj wartości „Number.isNaN” we wszystkich warunkach.", "Use_element_access_for_0_95145": "Użyj dostępu do elementu w przypadku elementu „{0}”", "Use_element_access_for_all_undeclared_properties_95146": "Użyj dostępu do elementu w przypadku wszystkich niezadeklarowanych właściwości.", "Use_synthetic_default_member_95016": "Użyj syntetycznej składowej „default”.", + "Using_0_subpath_1_with_target_2_6404": "Używanie „{0}” ścieżki podrzędnej „{1}” z elementem docelowym „{2}”.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Używanie ciągu w instrukcji „for...of” jest obsługiwane tylko w języku ECMAScript 5 lub nowszym.", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Użycie elementu --build, -b sprawi, że narzędzie tsc będzie zachowywało się bardziej jak orkiestrator kompilacji niż kompilator. Ta opcja jest wykorzystywana do wyzwalania kompilacji projektów złożonych, o których dowiesz się więcej na stronie {0}", "Using_compiler_options_of_project_reference_redirect_0_6215": "Using compiler options of project reference redirect '{0}'.", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 6a80289a9eae6..a2a5eacbd2fce 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -501,9 +501,16 @@ declare namespace ts.server.protocol { arguments: OrganizeImportsRequestArgs; } type OrganizeImportsScope = GetCombinedCodeFixScope; + const enum OrganizeImportsMode { + All = "All", + SortAndCombine = "SortAndCombine", + RemoveUnused = "RemoveUnused" + } interface OrganizeImportsRequestArgs { scope: OrganizeImportsScope; + /** @deprecated Use `mode` instead */ skipDestructiveCodeActions?: boolean; + mode?: OrganizeImportsMode; } interface OrganizeImportsResponse extends Response { body: readonly FileCodeEdits[]; @@ -853,12 +860,14 @@ declare namespace ts.server.protocol { command: CommandTypes.References; } interface ReferencesResponseItem extends FileSpanWithContext { - /** Text of line containing the reference. Including this - * with the response avoids latency of editor loading files - * to show text of reference line (the server already has - * loaded the referencing files). + /** + * Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has loaded the referencing files). + * + * If {@link UserPreferences.disableLineTextInReferences} is enabled, the property won't be filled */ - lineText: string; + lineText?: string; /** * True if reference is a write location, false otherwise. */ @@ -2704,6 +2713,10 @@ declare namespace ts.server.protocol { readonly includeInlayFunctionLikeReturnTypeHints?: boolean; readonly includeInlayEnumMemberValueHints?: boolean; readonly autoImportFileExcludePatterns?: string[]; + /** + * Indicates whether {@link ReferencesResponseItem.lineText} is supported. + */ + readonly disableLineTextInReferences?: boolean; } interface CompilerOptions { allowJs?: boolean; diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index 50245312a05dd..cec13e7f807ce 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "O suporte experimental de decorador é um recurso que está sujeito a alterações em uma liberação futura. Configure a opção 'experimentalDecorators' em seu 'tsconfig' ou 'jsconfig' para remover este aviso.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Tipo de resolução de módulo especificado explicitamente: '{0}'.", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "A exponenciação não pode ser executada nos valores 'bigint', a menos que a opção 'target' esteja definida como 'es2016' ou posterior.", + "Export_0_from_module_1_90059": "Exportar '{0}' do módulo '{1}'", + "Export_all_referenced_locals_90060": "Exportar todos os locais referenciados", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Não é possível usar a atribuição de exportação durante o direcionamento para módulos de ECMAScript. Use a 'exportação padrão' ou outro formato de módulo em vez disso.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "A atribuição de exportação não tem suporte quando o sinalizador '--module' é 'system'.", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Exportar conflitos de declaração com declaração exportada de '{0}'.", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Fazer com que o keyof retorne apenas cadeias de caracteres, números ou símbolos. Opção herdada.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Tornar a chamada 'super()' a primeira instrução no construtor", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "O tipo de objeto mapeado implicitamente tem um tipo de modelo 'any'.", + "Matched_0_condition_1_6403": "'{0}' correspondente à condição '{1}'.", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Correspondido por padrão de inclusão padrão '**/*'", "Matched_by_include_pattern_0_in_1_1407": "Correspondência pelo padrão de inclusão '{0}' em '{1}'", "Member_0_implicitly_has_an_1_type_7008": "O membro '{0}' implicitamente tem um tipo '{1}'.", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "A resolução para o módulo '{0}' foi encontrada no cache do local '{1}'.", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "A resolução para a diretiva de referência de tipo '{0}' foi encontrada no cache a partir do local '{1}'.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Resolva 'keyof' somente para nomes de propriedades com valores de cadeia de caracteres (sem números nem símbolos).", + "Resolving_in_0_mode_with_conditions_1_6402": "Resolvendo no modo {0} com condições {1}.", "Resolving_module_0_from_1_6086": "======== Resolvendo módulo '{0}' de '{1}'. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Resolvendo nome de módulo '{0}' relativo à URL base '{1}' - '{2}'.", "Resolving_real_path_for_0_result_1_6130": "Resolvendo o caminho real de '{0}', resultado '{1}'.", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "Arquivo raiz especificado para compilação", "STRATEGY_6039": "ESTRATÉGIA", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Salvar arquivos .tsbuildinfo para permitir a compilação incremental de projetos.", + "Saw_non_matching_condition_0_6405": "Viu condição de não correspondência '{0}'.", "Scoped_package_detected_looking_in_0_6182": "Pacote com escopo detectado, procurando no '{0}'", "Selection_is_not_a_valid_statement_or_statements_95155": "A seleção não é uma instrução ou instruções válidas", "Selection_is_not_a_valid_type_node_95133": "A seleção não é um nó de tipo válido", @@ -1474,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "A propriedade '{0}' da marca desse JSX espera um único filho do tipo '{1}', mas vários filhos foram fornecidos.", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "A propriedade '{0}' da marca desse JSX espera o tipo '{1}' que requer vários filhos, mas somente um único filho foi fornecido.", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Esta comparação parece não ser intencional porque os tipos '{0}' e '{1}' não têm sobreposição.", + "This_condition_will_always_return_0_2845": "Esta condição sempre retornará '{0}'.", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Essa condição sempre retornará '{0}', pois o JavaScript compara objetos por referência, não por valor.", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Esta condição sempre retornará verdadeiro, já que este '{0}' está sempre definido.", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Esta condição sempre retornará verdadeira, uma vez que esta função foi sempre definida. Você pretendia chamá-la em vez disso?", @@ -1648,9 +1654,12 @@ "Updating_output_of_project_0_6373": "Atualizando a saída do projeto '{0}'...", "Updating_output_timestamps_of_project_0_6359": "Atualizando os carimbos de data/hora de saída do projeto '{0}'...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Atualizando os carimbos de data/hora de saída inalterados do projeto '{0}'...", + "Use_0_95174": "Use `{0}`.", + "Use_Number_isNaN_in_all_conditions_95175": "Use `Number.isNaN` em todas as condições.", "Use_element_access_for_0_95145": "Usar o acesso de elemento para '{0}'", "Use_element_access_for_all_undeclared_properties_95146": "Usar o acesso de elemento para todas as propriedades não declaradas.", "Use_synthetic_default_member_95016": "Use o membro sintético 'padrão'.", + "Using_0_subpath_1_with_target_2_6404": "Usando '{0}' subcaminho '{1}' com destino '{2}'.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Há suporte para o uso de uma cadeia de caracteres em uma instrução 'for...of' somente no ECMAScript 5 e superior.", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Usar --build, -b fará com que o tsc se comporte mais como um orquestrador de build do que como um compilador. Isso é usado para acionar a construção de projetos compostos sobre os quais você pode aprender mais em {0}", "Using_compiler_options_of_project_reference_redirect_0_6215": "Usando as opções do compilador de redirecionamento de referência do projeto '{0}'.", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index 2e5431012e9a1..1de4b2b1c0c16 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Экспериментальная поддержка для декораторов — это функция, которая будет изменена в будущем выпуске. Задайте параметр \"experimentalDecorators\" в \"tsconfig\" или \"jsconfig\", чтобы удалить это предупреждение.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Явно указанный тип разрешения модуля: \"{0}\".", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "Невозможно выполнить возведение в степень для значений \"bigint\", если для параметра \"target\" не задана версия \"es2016\" или более поздняя версия.", + "Export_0_from_module_1_90059": "Экспорт \"{0}\" из модуля \"{1}\"", + "Export_all_referenced_locals_90060": "Экспортировать все локальные объекты, на которые указывают ссылки", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Назначение экспорта невозможно использовать при разработке для модулей ECMAScript. Попробуйте использовать \"export default\" или другой формат модуля.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Назначение экспорта не поддерживается, если флаг \"--module\" имеет значение \"system\".", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Объявление экспорта конфликтует с экспортированным объявлением \"{0}\".", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Сделать так, чтобы keyof возвращал только строки, а не строки, числа или символы. Устаревший вариант.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Сделайте вызов \"super()\" первой инструкцией в конструкторе", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Сопоставленный объект неявно имеет тип шаблона \"любой\".", + "Matched_0_condition_1_6403": "Соответствие: \"{0}\", условие: \"{1}\".", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Сопоставление по умолчанию включает шаблон '**/*'", "Matched_by_include_pattern_0_in_1_1407": "Соответствует шаблону включения \"{0}\" в \"{1}\".", "Member_0_implicitly_has_an_1_type_7008": "Элемент \"{0}\" неявно имеет тип \"{1}\".", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "Разрешение для модуля \"{0}\" найдено в кэше из расположения \"{1}\".", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "Разрешение для директивы ссылки на тип \"{0}\" обнаружено в кэше из расположения \"{1}\".", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "Разрешать \"keyof\" только в имена свойств со строковым значением (не числа и не символы).", + "Resolving_in_0_mode_with_conditions_1_6402": "Разрешение в режиме {0} с условиями {1}.", "Resolving_module_0_from_1_6086": "======== Идет разрешение модуля \"{0}\" из \"{1}\". ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "Идет разрешение имени модуля \"{0}\" относительного к базовому URL-адресу \"{1}\" — \"{2}\".", "Resolving_real_path_for_0_result_1_6130": "Разрешается реальный путь для \"{0}\"; результат: \"{1}\".", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "Корневой файл, указанный для компиляции", "STRATEGY_6039": "СТРАТЕГИЯ", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Сохраните файлы .tsbuildinfo, чтобы обеспечить возможность добавочной компиляции проектов.", + "Saw_non_matching_condition_0_6405": "Обнаружено несоответствующее условие \"{0}\".", "Scoped_package_detected_looking_in_0_6182": "Обнаружен пакет, относящийся к области; поиск в \"{0}\"", "Selection_is_not_a_valid_statement_or_statements_95155": "Выделенный фрагмент не является допустимым оператором или операторами.", "Selection_is_not_a_valid_type_node_95133": "Выбранный элемент не является допустимым узлом типа.", @@ -1474,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "Свойство \"{0}\" этого тега JSX ожидает один дочерний объект типа \"{1}\", однако было предоставлено несколько дочерних объектов.", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "Свойство \"{0}\" этого тега JSX ожидает тип \"{1}\", требующий несколько дочерних объектов, однако был предоставлен только один дочерний объект.", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "Это сравнение кажется непреднамеренным, поскольку типы \"{0}\" и \"{1}\" не перекрываются.", + "This_condition_will_always_return_0_2845": "Это условие всегда возвращает \"{0}\".", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "Это условие всегда будет возвращать ''{0}'', так как JavaScript сравнивает объекты по ссылке, а не по значению.", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Это условие всегда будет возвращать значение true, поскольку функция \"{0}\" всегда определена.", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "Это условие будет всегда возвращать значение true, поскольку функция всегда определена. Возможно, вы хотите вызвать ее?", @@ -1648,9 +1654,12 @@ "Updating_output_of_project_0_6373": "Обновление выходных данных проекта \"{0}\"...", "Updating_output_timestamps_of_project_0_6359": "Обновление меток времени в выходных данных проекта \"{0}\"...", "Updating_unchanged_output_timestamps_of_project_0_6371": "Обновление меток времени в неизменившихся выходных данных проекта \"{0}\"...", + "Use_0_95174": "Использовать \"{0}\".", + "Use_Number_isNaN_in_all_conditions_95175": "Использовать \"Number.isNaN\" во всех условиях.", "Use_element_access_for_0_95145": "Использовать доступ к элементам для \"{0}\".", "Use_element_access_for_all_undeclared_properties_95146": "Использовать доступ к элементам для всех необъявленных свойств.", "Use_synthetic_default_member_95016": "Используйте искусственный элемент \"default\".", + "Using_0_subpath_1_with_target_2_6404": "Использование \"{0}\", вложенный путь: \"{1}\", целевой объект: \"{2}\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Использование строки для оператора for...of поддерживается только в ECMAScript 5 и более поздних версиях.", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "Использование --build,-b заставит TSC вести себя больше как оркестратор сборки, чем как компилятор. Это используется для запуска создания составных проектов, о которых можно узнать больше на {0}", "Using_compiler_options_of_project_reference_redirect_0_6215": "Использование параметров компилятора для перенаправления ссылки на проект \"{0}\".", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 1745a7341a898..36a7594ca577b 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Dekoratörler için sunulan deneysel destek özelliği, sonraki sürümlerde değiştirilebilir. Bu uyarıyı kaldırmak için 'tsconfig' veya 'jsconfig' dosyanızdaki 'experimentalDecorators' seçeneğini ayarlayın.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Açık olarak belirtilen modül çözümleme türü: '{0}'.", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "'target' seçeneği 'es2016' veya üzeri olarak belirlenmedikçe 'bigint' değerlerinde üs olarak gösterme yapılamaz.", + "Export_0_from_module_1_90059": "'{1}' modülünden '{0}' öğesini dışarı aktar", + "Export_all_referenced_locals_90060": "Başvurulan tüm yerel ayarları dışarı aktar", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript modülleri hedeflenirken dışarı aktarma ataması kullanılamaz. Bunun yerine 'export default' veya başka bir modül biçimi kullanmayı deneyin.", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "'--module' bayrağı 'system' ise dışarı aktarma ataması desteklenmez.", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Dışarı aktarma bildirimi, dışarı aktarılan '{0}' bildirimiyle çakışıyor.", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "Dize, sayı veya simge yerine yalnızca dönüş dizelerinin anahtarını oluşturun. Eski seçenek.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Oluşturucudaki ilk deyime 'super()' tarafından çağrı yapılmasını sağla", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Eşleştirilmiş nesne türü örtük olarak 'any' şablon türüne sahip.", + "Matched_0_condition_1_6403": "'{0}' koşulu '{1}' eşleşti.", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "Varsayılan '**/*' ekleme deseniyle eşleşti", "Matched_by_include_pattern_0_in_1_1407": "'{1}' içindeki '{0}' ekleme desenine göre eşleştirildi", "Member_0_implicitly_has_an_1_type_7008": "'{0}' üyesi örtük olarak '{1}' türüne sahip.", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "'{0}' modülünün çözümü '{1}' konumundaki önbellekte bulundu.", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "'{0}' tür başvurusu yönergesinin çözümlemesi '{1}' konumundaki önbellekte bulundu.", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "'Keyof' değerini yalnızca dize değerli özellik adlarına (sayılar veya simgeler olmadan) çözümleyin.", + "Resolving_in_0_mode_with_conditions_1_6402": "{0} modunda {1} koşullarıyla çözümleniyor.", "Resolving_module_0_from_1_6086": "======== '{0}' modülü '{1}' öğesinden çözümleniyor. ========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "'{0}' modül adı, '{1}' - '{2}' temel url'sine göre çözümleniyor.", "Resolving_real_path_for_0_result_1_6130": "'{0}' için gerçek yol çözümleniyor, sonuç: '{1}'.", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "Derleme için belirtilen kök dosyası", "STRATEGY_6039": "STRATEJİ", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "Projelerin artımlı derlenmesini sağlamak için .tsbuildinfo dosyalarını kaydedin.", + "Saw_non_matching_condition_0_6405": "Eşleşmeyen koşul '{0}' görüldü.", "Scoped_package_detected_looking_in_0_6182": "Kapsamlı paket algılandı, '{0}' içinde aranıyor", "Selection_is_not_a_valid_statement_or_statements_95155": "Seçim geçerli bir veya daha fazla deyim değil", "Selection_is_not_a_valid_type_node_95133": "Seçim geçerli bir tür düğümü değil", @@ -1474,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "Bu JSX etiketinin '{0}' özelliği, '{1}' türünde tek bir alt öğe bekliyor ancak birden çok alt öğe sağlandı.", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "Bu JSX etiketinin '{0}' özelliği, birden çok alt öğe gerektiren '{1}' türünü bekliyor ancak yalnızca tek bir alt öğe sağlandı.", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "'{0}' ve '{1}' türlerinde çakışma olmadığından bu karşılaştırma yanlışlıkla yapılmış gibi görünüyor.", + "This_condition_will_always_return_0_2845": "Bu koşul her zaman '{0}' döndürür.", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "JavaScript nesneleri değer göre değil başvuruya göre karşılaştırdığından bu koşul her zaman '{0}' değerini döndürür.", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "Bu '{0}' her zaman tanımlandığı için bu koşul her zaman doğru olacaktır.", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "İşlev her zaman tanımlı olduğundan bu koşul her zaman true döndürür. Bunun yerine işlevi çağırmayı mı istediniz?", @@ -1648,9 +1654,12 @@ "Updating_output_of_project_0_6373": "'{0}' projesinin çıkışı güncelleştiriliyor...", "Updating_output_timestamps_of_project_0_6359": "'{0}' projesinin çıkış zaman damgaları güncelleştiriliyor...", "Updating_unchanged_output_timestamps_of_project_0_6371": "'{0}' projesinin değiştirilmemiş çıkış zaman damgaları güncelleştiriliyor...", + "Use_0_95174": "`{0}` kullanın.", + "Use_Number_isNaN_in_all_conditions_95175": "Tüm koşullarda `Number.isNaN` kullanın.", "Use_element_access_for_0_95145": "'{0}' için öğe erişimi kullan", "Use_element_access_for_all_undeclared_properties_95146": "Tüm bildirilmemiş özellikler için öğe erişimi kullanın.", "Use_synthetic_default_member_95016": "Yapay 'default' üyesini kullanın.", + "Using_0_subpath_1_with_target_2_6404": "Hedef '{2}' ile '{0}' alt yol '{1}' kullanılıyor.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' deyiminde dize kullanma yalnızca ECMAScript 5 veya üzerinde desteklenir.", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "--build kullanarak -b, tsc’nin derleyici yerine derleme düzenleyici gibi davranmasına yol açar. Bu, kompozit projeler oluşturmayı tetiklemek için kullanılır. Daha fazla bilgi edinmek için bkz. {0}", "Using_compiler_options_of_project_reference_redirect_0_6215": "'{0}' proje başvurusu yeniden yönlendirmesinin derleyici seçenekleri kullanılıyor.", diff --git a/lib/tsc.js b/lib/tsc.js index d58b282648d46..ab0a0ed2848d7 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -69,7 +69,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) { var ts; (function (ts) { ts.versionMajorMinor = "4.9"; - ts.version = "".concat(ts.versionMajorMinor, ".1-beta"); + ts.version = "".concat(ts.versionMajorMinor, ".2-rc"); var NativeCollections; (function (NativeCollections) { var globals = typeof globalThis !== "undefined" ? globalThis : @@ -1606,8 +1606,8 @@ var ts; return compareValues(a === null || a === void 0 ? void 0 : a.start, b === null || b === void 0 ? void 0 : b.start) || compareValues(a === null || a === void 0 ? void 0 : a.length, b === null || b === void 0 ? void 0 : b.length); } ts.compareTextSpans = compareTextSpans; - function min(a, b, compare) { - return compare(a, b) === -1 ? a : b; + function min(items, compare) { + return reduceLeft(items, function (x, y) { return compare(x, y) === -1 ? x : y; }); } ts.min = min; function compareStringsCaseInsensitive(a, b) { @@ -2744,7 +2744,9 @@ var ts; (function (ts) { var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var buildPartRegExp = /^[a-z0-9-]+$/i; var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; var Version = (function () { function Version(major, minor, patch, prerelease, build) { @@ -2759,13 +2761,15 @@ var ts; ts.Debug.assert(major >= 0, "Invalid argument: major"); ts.Debug.assert(minor >= 0, "Invalid argument: minor"); ts.Debug.assert(patch >= 0, "Invalid argument: patch"); - ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); - ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + var prereleaseArray = prerelease ? ts.isArray(prerelease) ? prerelease : prerelease.split(".") : ts.emptyArray; + var buildArray = build ? ts.isArray(build) ? build : build.split(".") : ts.emptyArray; + ts.Debug.assert(ts.every(prereleaseArray, function (s) { return prereleasePartRegExp.test(s); }), "Invalid argument: prerelease"); + ts.Debug.assert(ts.every(buildArray, function (s) { return buildPartRegExp.test(s); }), "Invalid argument: build"); this.major = major; this.minor = minor; this.patch = patch; - this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; - this.build = build ? build.split(".") : ts.emptyArray; + this.prerelease = prereleaseArray; + this.build = buildArray; } Version.tryParse = function (text) { var result = tryParseComponents(text); @@ -2792,6 +2796,10 @@ var ts; default: return ts.Debug.assertNever(field); } }; + Version.prototype.with = function (fields) { + var _a = fields.major, major = _a === void 0 ? this.major : _a, _b = fields.minor, minor = _b === void 0 ? this.minor : _b, _c = fields.patch, patch = _c === void 0 ? this.patch : _c, _d = fields.prerelease, prerelease = _d === void 0 ? this.prerelease : _d, _e = fields.build, build = _e === void 0 ? this.build : _e; + return new Version(major, minor, patch, prerelease, build); + }; Version.prototype.toString = function () { var result = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); if (ts.some(this.prerelease)) @@ -2800,7 +2808,7 @@ var ts; result += "+".concat(this.build.join(".")); return result; }; - Version.zero = new Version(0, 0, 0); + Version.zero = new Version(0, 0, 0, ["0"]); return Version; }()); ts.Version = Version; @@ -2950,19 +2958,20 @@ var ts; break; case "<": case ">=": - comparators.push(createComparator(operator, version)); + comparators.push(isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version.with({ prerelease: "0" })) : + createComparator(operator, version)); break; case "<=": case ">": - comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : - isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major").with({ prerelease: "0" })) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor").with({ prerelease: "0" })) : createComparator(operator, version)); break; case "=": case undefined: if (isWildcard(minor) || isWildcard(patch)) { - comparators.push(createComparator(">=", version)); - comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + comparators.push(createComparator(">=", version.with({ prerelease: "0" }))); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor").with({ prerelease: "0" }))); } else { comparators.push(createComparator("=", version)); @@ -4213,7 +4222,7 @@ var ts; }; } function createSystemWatchFunctions(_a) { - var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; + var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; var pollingWatches = new ts.Map(); var fsWatches = new ts.Map(); var fsWatchesRecursive = new ts.Map(); @@ -4272,7 +4281,7 @@ var ts; default: return useNonPollingWatchers ? generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : - { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.UseFsEvents }; + { watchFile: ts.WatchFileKind.UseFsEvents }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -4495,7 +4504,6 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, - defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, inodeWatching: isLinuxOrMacOs, sysLog: sysLog, }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; @@ -6741,6 +6749,10 @@ var ts; Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted: diag(6399, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399", "Project '{0}' is out of date because buildinfo file '{1}' indicates that some of the changes were not emitted"), Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files: diag(6400, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400", "Project '{0}' is up to date but needs to update timestamps of output files that are older than input files"), Project_0_is_out_of_date_because_there_was_error_reading_file_1: diag(6401, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401", "Project '{0}' is out of date because there was error reading file '{1}'"), + Resolving_in_0_mode_with_conditions_1: diag(6402, ts.DiagnosticCategory.Message, "Resolving_in_0_mode_with_conditions_1_6402", "Resolving in {0} mode with conditions {1}."), + Matched_0_condition_1: diag(6403, ts.DiagnosticCategory.Message, "Matched_0_condition_1_6403", "Matched '{0}' condition '{1}'."), + Using_0_subpath_1_with_target_2: diag(6404, ts.DiagnosticCategory.Message, "Using_0_subpath_1_with_target_2_6404", "Using '{0}' subpath '{1}' with target '{2}'."), + Saw_non_matching_condition_0: diag(6405, ts.DiagnosticCategory.Message, "Saw_non_matching_condition_0_6405", "Saw non-matching condition '{0}'."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -7057,6 +7069,8 @@ var ts; Remove_type_from_import_of_0_from_1: diag(90056, ts.DiagnosticCategory.Message, "Remove_type_from_import_of_0_from_1_90056", "Remove 'type' from import of '{0}' from \"{1}\""), Add_import_from_0: diag(90057, ts.DiagnosticCategory.Message, "Add_import_from_0_90057", "Add import from \"{0}\""), Update_import_from_0: diag(90058, ts.DiagnosticCategory.Message, "Update_import_from_0_90058", "Update import from \"{0}\""), + Export_0_from_module_1: diag(90059, ts.DiagnosticCategory.Message, "Export_0_from_module_1_90059", "Export '{0}' from module '{1}'"), + Export_all_referenced_locals: diag(90060, ts.DiagnosticCategory.Message, "Export_all_referenced_locals_90060", "Export all referenced locals"), 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}"), @@ -8341,7 +8355,7 @@ var ts; return -1; } function peekExtendedUnicodeEscape() { - if (languageVersion >= 2 && codePointAt(text, pos + 1) === 117 && codePointAt(text, pos + 2) === 123) { + if (codePointAt(text, pos + 1) === 117 && codePointAt(text, pos + 2) === 123) { var start_2 = pos; pos += 3; var escapedValueString = scanMinimumNumberOfHexDigits(1, false); @@ -17276,6 +17290,32 @@ var ts; return parameter.kind === 343 ? (_a = parameter.typeExpression) === null || _a === void 0 ? void 0 : _a.type : parameter.type; } ts.getParameterTypeNode = getParameterTypeNode; + function isTypeDeclaration(node) { + switch (node.kind) { + case 165: + case 260: + case 261: + case 262: + case 263: + case 348: + case 341: + case 342: + return true; + case 270: + return node.isTypeOnly; + case 273: + case 278: + return node.parent.parent.isTypeOnly; + default: + return false; + } + } + ts.isTypeDeclaration = isTypeDeclaration; + function canHaveExportModifier(node) { + return ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) || isTypeDeclaration(node) || (ts.isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node)); + } + ts.canHaveExportModifier = canHaveExportModifier; })(ts || (ts = {})); var ts; (function (ts) { @@ -18476,7 +18516,7 @@ var ts; nextAutoGenerateId++; return node; } - function createIdentifier(text, typeArguments, originalKeywordKind) { + function createIdentifier(text, typeArguments, originalKeywordKind, hasExtendedUnicodeEscape) { var node = createBaseIdentifier(text, originalKeywordKind); if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -18484,6 +18524,10 @@ var ts; if (node.originalKeywordKind === 133) { node.transformFlags |= 67108864; } + if (hasExtendedUnicodeEscape) { + node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + node.transformFlags |= 1024; + } return node; } function updateIdentifier(node, typeArguments) { @@ -23160,7 +23204,7 @@ var ts; importName: "__generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; ts.createBindingHelper = { name: "typescript:commonjscreatebinding", @@ -26751,8 +26795,9 @@ var ts; var pos = getNodePos(); var originalKeywordKind = token(); var text = internIdentifier(scanner.getTokenValue()); + var hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape(); nextTokenWithoutCheck(); - return finishNode(factory.createIdentifier(text, undefined, originalKeywordKind), pos); + return finishNode(factory.createIdentifier(text, undefined, originalKeywordKind, hasExtendedUnicodeEscape), pos); } if (token() === 80) { parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); @@ -34480,12 +34525,22 @@ var ts; return !isCommandLineOnly && category !== undefined && (!categoriesToSkip.includes(category) || compilerOptionsMap.has(name)); } function writeConfigurations() { - var categorizedOptions = ts.createMultiMap(); + var categorizedOptions = new ts.Map(); + categorizedOptions.set(ts.Diagnostics.Projects, []); + categorizedOptions.set(ts.Diagnostics.Language_and_Environment, []); + categorizedOptions.set(ts.Diagnostics.Modules, []); + categorizedOptions.set(ts.Diagnostics.JavaScript_Support, []); + categorizedOptions.set(ts.Diagnostics.Emit, []); + categorizedOptions.set(ts.Diagnostics.Interop_Constraints, []); + categorizedOptions.set(ts.Diagnostics.Type_Checking, []); + categorizedOptions.set(ts.Diagnostics.Completeness, []); for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { var option = optionDeclarations_1[_i]; - var category = option.category; if (isAllowedOptionForOutput(option)) { - categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + var listForCategory = categorizedOptions.get(option.category); + if (!listForCategory) + categorizedOptions.set(option.category, listForCategory = []); + listForCategory.push(option); } } var marginLength = 0; @@ -34495,7 +34550,7 @@ var ts; if (entries.length !== 0) { entries.push({ value: "" }); } - entries.push({ value: "/* ".concat(category, " */") }); + entries.push({ value: "/* ".concat(ts.getLocaleSpecificMessage(category), " */") }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -36224,6 +36279,9 @@ var ts; requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; + if (traceEnabled && ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) <= ts.ModuleResolutionKind.NodeNext) { + trace(host, ts.Diagnostics.Resolving_in_0_mode_with_conditions_1, features & NodeResolutionFeatures.EsmMode ? "ESM" : "CJS", conditions.map(function (c) { return "'".concat(c, "'"); }).join(", ")); + } var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { @@ -36753,7 +36811,7 @@ var ts; } if (mainExport) { var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, false); - return loadModuleFromTargetImportOrExport(mainExport, "", false); + return loadModuleFromTargetImportOrExport(mainExport, "", false, "."); } } else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) { @@ -36828,7 +36886,7 @@ var ts; var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!ts.endsWith(moduleName, ts.directorySeparator) && moduleName.indexOf("*") === -1 && ts.hasProperty(lookupTable, moduleName)) { var target = lookupTable[moduleName]; - return loadModuleFromTargetImportOrExport(target, "", false); + return loadModuleFromTargetImportOrExport(target, "", false, moduleName); } var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), comparePatternKeys); for (var _i = 0, expandingKeys_1 = expandingKeys; _i < expandingKeys_1.length; _i++) { @@ -36837,17 +36895,17 @@ var ts; var target = lookupTable[potentialTarget]; var starPos = potentialTarget.indexOf("*"); var subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); - return loadModuleFromTargetImportOrExport(target, subpath, true); + return loadModuleFromTargetImportOrExport(target, subpath, true, potentialTarget); } else if (ts.endsWith(potentialTarget, "*") && ts.startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length - 1); - return loadModuleFromTargetImportOrExport(target, subpath, true); + return loadModuleFromTargetImportOrExport(target, subpath, true, potentialTarget); } else if (ts.startsWith(moduleName, potentialTarget)) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length); - return loadModuleFromTargetImportOrExport(target, subpath, false); + return loadModuleFromTargetImportOrExport(target, subpath, false, potentialTarget); } } function matchesPatternWithTrailer(target, name) { @@ -36861,7 +36919,7 @@ var ts; } function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) { return loadModuleFromTargetImportOrExport; - function loadModuleFromTargetImportOrExport(target, subpath, pattern) { + function loadModuleFromTargetImportOrExport(target, subpath, pattern, key) { if (typeof target === "string") { if (!pattern && subpath.length > 0 && !ts.endsWith(target, "/")) { if (state.traceEnabled) { @@ -36872,6 +36930,8 @@ var ts; if (!ts.startsWith(target, "./")) { if (isImports && !ts.startsWith(target, "../") && !ts.startsWith(target, "/") && !ts.isRootedDiskPath(target)) { var combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath; + traceIfEnabled(state, ts.Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup); + traceIfEnabled(state, ts.Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/"); var result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, [extensions], redirectedReference); return toSearchResult(result.resolvedModule ? { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId, originalPath: result.resolvedModule.originalPath } : undefined); } @@ -36896,6 +36956,9 @@ var ts; } return toSearchResult(undefined); } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); + } var finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); var inputLink = tryLoadInputFileForPath(finalPath, subpath, ts.combinePaths(scope.packageDirectory, "package.json"), isImports); if (inputLink) @@ -36905,14 +36968,18 @@ var ts; else if (typeof target === "object" && target !== null) { if (!Array.isArray(target)) { for (var _i = 0, _a = ts.getOwnKeys(target); _i < _a.length; _i++) { - var key = _a[_i]; - if (key === "default" || state.conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(state.conditions, key)) { - var subTarget = target[key]; - var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern); + var condition = _a[_i]; + if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) { + traceIfEnabled(state, ts.Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition); + var subTarget = target[condition]; + var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key); if (result) { return result; } } + else { + traceIfEnabled(state, ts.Diagnostics.Saw_non_matching_condition_0, condition); + } } return undefined; } @@ -36925,7 +36992,7 @@ var ts; } for (var _b = 0, target_2 = target; _b < target_2.length; _b++) { var elem = target_2[_b]; - var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern); + var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern, key); if (result) { return result; } @@ -37276,6 +37343,15 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } + function traceIfEnabled(state, diagnostic) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (state.traceEnabled) { + trace.apply(void 0, __spreadArray([state.host, diagnostic], args, false)); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -40580,6 +40656,12 @@ var ts; getOptionalType: function () { return optionalType; }, getPromiseType: function () { return getGlobalPromiseType(false); }, getPromiseLikeType: function () { return getGlobalPromiseLikeType(false); }, + getAsyncIterableType: function () { + var type = getGlobalAsyncIterableType(false); + if (type === emptyGenericType) + return undefined; + return type; + }, isSymbolAccessible: isSymbolAccessible, isArrayType: isArrayType, isTupleType: isTupleType, @@ -41366,8 +41448,8 @@ var ts; return symbol; } if (symbol.flags & 2097152) { - var target = resolveAlias(symbol); - if (target === unknownSymbol || target.flags & meaning) { + var targetFlags = getAllSymbolFlags(symbol); + if (targetFlags & meaning) { return symbol; } } @@ -41857,8 +41939,8 @@ var ts; !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && + !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; var suggestedLib = void 0; @@ -41926,7 +42008,7 @@ var ts; } } if (result && errorLocation && meaning & 111551 && result.flags & 2097152 && !(result.flags & 111551) && !ts.isValidTypeOnlyAliasUseSite(errorLocation)) { - var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); + var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551); if (typeOnlyDeclaration) { var message = typeOnlyDeclaration.kind === 278 ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type @@ -42079,7 +42161,7 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (111551 & ~1024)) { + if (meaning & 111551) { if (isPrimitiveTypeName(name)) { if (isExtendedByInterface(errorLocation)) { error(errorLocation, ts.Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, ts.unescapeLeadingUnderscores(name)); @@ -42090,7 +42172,8 @@ var ts; return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 & ~111551, undefined, undefined, false)); - if (symbol && !(symbol.flags & 1024)) { + var allFlags = symbol && getAllSymbolFlags(symbol); + if (symbol && allFlags !== undefined && !(allFlags & 111551)) { var rawName = ts.unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName); @@ -42138,16 +42221,16 @@ var ts; } return false; } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (111551 & ~1024 & ~788968)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~111551, undefined, undefined, false)); + function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) { + if (meaning & (111551 & ~788968)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (788968 & ~1024 & ~111551)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 | 1024) & ~788968, undefined, undefined, false)); + else if (meaning & (788968 & ~111551)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1536, undefined, undefined, false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -42678,6 +42761,30 @@ var ts; } return undefined; } + function getAllSymbolFlags(symbol) { + var flags = symbol.flags; + var seenSymbols; + while (symbol.flags & 2097152) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return 67108863; + } + if (target === symbol || (seenSymbols === null || seenSymbols === void 0 ? void 0 : seenSymbols.has(target))) { + break; + } + if (target.flags & 2097152) { + if (seenSymbols) { + seenSymbols.add(target); + } + else { + seenSymbols = new ts.Set([symbol, target]); + } + } + flags |= target.flags; + symbol = target; + } + return flags; + } function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) { if (!aliasDeclaration || ts.isPropertyAccessExpression(aliasDeclaration)) return false; @@ -42700,19 +42807,25 @@ var ts; } return !!aliasDeclarationLinks.typeOnlyDeclaration; } - function getTypeOnlyAliasDeclaration(symbol) { + function getTypeOnlyAliasDeclaration(symbol, include) { if (!(symbol.flags & 2097152)) { return undefined; } var links = getSymbolLinks(symbol); - return links.typeOnlyDeclaration || undefined; + if (include === undefined) { + return links.typeOnlyDeclaration || undefined; + } + if (links.typeOnlyDeclaration) { + return getAllSymbolFlags(resolveAlias(links.typeOnlyDeclaration.symbol)) & include ? links.typeOnlyDeclaration : undefined; + } + return undefined; } function markExportAsReferenced(node) { var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 111551) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol)); + ((getAllSymbolFlags(target) & 111551) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -42726,8 +42839,7 @@ var ts; if (!node) return ts.Debug.fail(); if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveSymbol(symbol); - if (target === unknownSymbol || target.flags & 111551) { + if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551) { checkExpressionCached(node.moduleReference); } } @@ -43457,7 +43569,7 @@ var ts; } function symbolIsValue(symbol, includeTypeOnlyMembers) { return !!(symbol.flags & 111551 || - symbol.flags & 2097152 && resolveAlias(symbol).flags & 111551 && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + symbol.flags & 2097152 && getAllSymbolFlags(symbol) & 111551 && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -43684,8 +43796,10 @@ var ts; if (symbolFromSymbolTable === symbol) { return true; } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { + var shouldResolveAlias = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278)); + symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + var flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + if (flags & meaning) { qualify = true; return true; } @@ -45791,7 +45905,7 @@ var ts; if (!e.propertyName) { var indices = ts.indicesOf(statements); var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); }); - if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) { + if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return ts.canHaveExportModifier(statements[i]); })) { for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) { var index_1 = associatedIndices_1[_i]; statements[index_1] = addExportModifier(statements[index_1]); @@ -45821,15 +45935,6 @@ var ts; } return statements; } - function canHaveExportModifier(node) { - return ts.isEnumDeclaration(node) || - ts.isVariableStatement(node) || - ts.isFunctionDeclaration(node) || - ts.isClassDeclaration(node) || - (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) || - ts.isInterfaceDeclaration(node) || - isTypeDeclaration(node); - } function addExportModifier(node) { var flags = (ts.getEffectiveModifierFlags(node) | 1) & ~2; return ts.factory.updateModifiers(node, flags); @@ -46014,7 +46119,7 @@ var ts; (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 && enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && - canHaveExportModifier(node)) { + ts.canHaveExportModifier(node)) { newModifierFlags |= 1; } if (addingDeclare && !(newModifierFlags & 1) && @@ -46067,7 +46172,7 @@ var ts; return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { - return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551); }); + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(getAllSymbolFlags(resolveSymbol(m)) & 111551); }); } function serializeModule(symbol, symbolName, modifierFlags) { var members = getNamespaceMembersForSerialization(symbol); @@ -47940,7 +48045,7 @@ var ts; links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType - : targetSymbol.flags & 111551 ? getTypeOfSymbol(targetSymbol) + : getAllSymbolFlags(targetSymbol) & 111551 ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; @@ -49575,7 +49680,17 @@ var ts; return !!(ts.getObjectFlags(type) & 32 && getMappedTypeModifiers(type) & 4); } function isGenericMappedType(type) { - return !!(ts.getObjectFlags(type) & 32) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + if (ts.getObjectFlags(type) & 32) { + var constraint = getConstraintTypeFromMappedType(type); + if (isGenericIndexType(constraint)) { + return true; + } + var nameType = getNameTypeFromMappedType(type); + if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) { + return true; + } + } + return false; } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -49974,7 +50089,7 @@ var ts; var propSet; var indexTypes; var isUnion = containingType.flags & 1048576; - var optionalFlag = isUnion ? 0 : 16777216; + var optionalFlag; var syntheticFlag = 4; var checkFlags = isUnion ? 0 : 8; var mergedInstantiations = false; @@ -49985,11 +50100,14 @@ var ts; var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop) { - if (isUnion) { - optionalFlag |= (prop.flags & 16777216); - } - else { - optionalFlag &= prop.flags; + if (prop.flags & 106500) { + optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : (optionalFlag = isUnion ? 0 : 16777216); + if (isUnion) { + optionalFlag |= (prop.flags & 16777216); + } + else { + optionalFlag &= prop.flags; + } } if (!singleProp) { singleProp = prop; @@ -50097,7 +50215,7 @@ var ts; propTypes.push(type); } ts.addRange(propTypes, indexTypes); - var result = createSymbol(4 | optionalFlag, name, syntheticFlag | checkFlags); + var result = createSymbol(4 | (optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : 0), name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && firstValueDeclaration) { result.valueDeclaration = firstValueDeclaration; @@ -52505,8 +52623,13 @@ var ts; return getStringLiteralType(text); } newTexts.push(text); - if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4); })) { - return stringType; + if (ts.every(newTexts, function (t) { return t === ""; })) { + if (ts.every(newTypes, function (t) { return !!(t.flags & 4); })) { + return stringType; + } + if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) { + return newTypes[0]; + } } var id = "".concat(getTypeListId(newTypes), "|").concat(ts.map(newTexts, function (t) { return t.length; }).join(","), "|").concat(newTexts.join("")); var type = templateLiteralTypes.get(id); @@ -52565,11 +52688,12 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 | 131072) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - type.flags & 268435456 && symbol === type.symbol ? type : - isGenericIndexType(type) || isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, isPatternLiteralPlaceholderType(type) && !(type.flags & 268435456) ? getTemplateLiteralType(["", ""], [type]) : type) : - type.flags & 128 ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type.flags & 134217728 ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : - type; + type.flags & 128 ? getStringLiteralType(applyStringMapping(symbol, type.value)) : + type.flags & 134217728 ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : + type.flags & 268435456 && symbol === type.symbol ? type : + type.flags & (1 | 4 | 268435456) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : + isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : + type; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -52722,7 +52846,15 @@ var ts; return accessFlags & 1 ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; } errorIfWritingToReadonlyIndex(indexInfo); - return accessFlags & 1 ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; + if ((accessFlags & 1) && + !(objectType.symbol && + objectType.symbol.flags & (256 | 128) && + (indexType.symbol && + indexType.flags & 1024 && + getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + return getUnionType([indexInfo.type, undefinedType]); + } + return indexInfo.type; } if (indexType.flags & 131072) { return neverType; @@ -52825,10 +52957,11 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 | 4 | 8 | 64)) || !!(type.flags & 268435456 && isPatternLiteralPlaceholderType(type.type)); + return !!(type.flags & (1 | 4 | 8 | 64)) || isPatternLiteralType(type); } function isPatternLiteralType(type) { - return !!(type.flags & 134217728) && ts.every(type.types, isPatternLiteralPlaceholderType); + return !!(type.flags & 134217728) && ts.every(type.types, isPatternLiteralPlaceholderType) || + !!(type.flags & 268435456) && isPatternLiteralPlaceholderType(type.type); } function isGenericType(type) { return !!getGenericObjectFlags(type); @@ -53056,18 +53189,18 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_20 = function () { + while (true) { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; - return "break"; + break; } var isUnwrapped = isTypicalNondistributiveConditional(root); var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { - return { value: wildcardType }; + return wildcardType; } var combinedMapper = void 0; if (root.inferTypeParameters) { @@ -53083,7 +53216,7 @@ var ts; } } } - if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) { + if (!checkTypeInstantiable) { inferTypes(context.inferences, checkType, instantiateType(extendsType, freshMapper), 512 | 1024); } var innerMapper = combineTypeMappers(freshMapper, context.mapper); @@ -53100,23 +53233,23 @@ var ts; var newRoot = falseType_1.root; if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) { root = newRoot; - return "continue"; + continue; } if (canTailRecurse(falseType_1, mapper)) { - return "continue"; + continue; } } result = instantiateType(falseType_1, mapper); - return "break"; + break; } if (inferredExtendsType.flags & 3 || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { var trueType_1 = getTypeFromTypeNode(root.node.trueType); var trueMapper = combinedMapper || mapper; if (canTailRecurse(trueType_1, trueMapper)) { - return "continue"; + continue; } result = instantiateType(trueType_1, trueMapper); - return "break"; + break; } } result = createType(16777216); @@ -53127,14 +53260,7 @@ var ts; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); - return "break"; - }; - while (true) { - var state_6 = _loop_20(); - if (typeof state_6 === "object") - return state_6.value; - if (state_6 === "break") - break; + break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; function canTailRecurse(newType, newMapper) { @@ -55350,7 +55476,7 @@ var ts; return 0; } } - var isPerformingCommonPropertyChecks = (relation !== comparableRelation || !(source.flags & 1048576) && isLiteralType(source)) && + var isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source)) && !(intersectionState & 2) && source.flags & (131068 | 524288 | 2097152) && source !== globalObjectType && target.flags & (524288 | 2097152) && isWeakType(target) && @@ -55378,12 +55504,6 @@ var ts; var result_7 = skipCaching ? unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) : recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags); - if (result_7 && !inPropertyCheck && (target.flags & 2097152 && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 && getApparentType(source).flags & 3670016 && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144); }))) { - inPropertyCheck = true; - result_7 &= recursiveTypeRelatedTo(source, target, reportErrors, 4, recursionFlags); - inPropertyCheck = false; - } if (result_7) { return result_7; } @@ -55492,7 +55612,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 ? reducedTarget.types : [reducedTarget]; } - var _loop_21 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -55545,9 +55665,9 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_7 = _loop_21(prop); - if (typeof state_7 === "object") - return state_7.value; + var state_6 = _loop_20(prop); + if (typeof state_6 === "object") + return state_6.value; } return false; } @@ -55727,8 +55847,7 @@ var ts; if (overflow) { return 0; } - var keyIntersectionState = intersectionState | (inPropertyCheck ? 8 : 0); - var id = getRelationKey(source, target, keyIntersectionState, relation, false); + var id = getRelationKey(source, target, intersectionState, relation, false); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 && !(entry & 4)) { @@ -55752,7 +55871,7 @@ var ts; targetStack = []; } else { - var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, keyIntersectionState, relation, true) : undefined; + var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, intersectionState, relation, true) : undefined; for (var i = 0; i < maybeCount; i++) { if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { return 3; @@ -55834,10 +55953,18 @@ var ts; function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { var saveErrorInfo = captureErrorCalculationState(); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo); - if (!result && (source.flags & 2097152 || source.flags & 262144 && target.flags & 1048576)) { - var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 ? source.types : [source], !!(target.flags & 1048576)); - if (constraint && !(constraint.flags & 131072) && everyType(constraint, function (c) { return c !== source; })) { - result = isRelatedTo(constraint, target, 1, false, undefined, intersectionState); + if (relation !== identityRelation) { + if (!result && (source.flags & 2097152 || source.flags & 262144 && target.flags & 1048576)) { + var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 ? source.types : [source], !!(target.flags & 1048576)); + if (constraint && everyType(constraint, function (c) { return c !== source; })) { + result = isRelatedTo(constraint, target, 1, false, undefined, intersectionState); + } + } + if (result && !inPropertyCheck && (target.flags & 2097152 && !isGenericObjectType(target) && source.flags & (524288 | 2097152) || + isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 && getApparentType(source).flags & 3670016 && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144); }))) { + inPropertyCheck = true; + result &= propertiesRelatedTo(source, target, reportErrors, undefined, 0); + inPropertyCheck = false; } } if (result) { @@ -55846,9 +55973,6 @@ var ts; return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo) { - if (intersectionState & 4) { - return propertiesRelatedTo(source, target, reportErrors, undefined, 0); - } var result; var originalErrorInfo; var varianceCheckFailed = false; @@ -55934,7 +56058,7 @@ var ts; if (relation === comparableRelation && sourceFlags & 262144) { var constraint = getConstraintOfTypeParameter(source); if (constraint && hasNonCircularBaseConstraint(source)) { - while (constraint && constraint.flags & 262144) { + while (constraint && someType(constraint, function (c) { return !!(c.flags & 262144); })) { if (result = isRelatedTo(constraint, target, 1, false)) { return result; } @@ -56324,11 +56448,11 @@ var ts; } var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_22 = function (combination) { + var _loop_21 = function (combination) { var hasMatch = false; outer: for (var _c = 0, _d = target.types; _c < _d.length; _c++) { var type = _d[_c]; - var _loop_23 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -56341,8 +56465,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_9 = _loop_23(i); - switch (state_9) { + var state_8 = _loop_22(i); + switch (state_8) { case "continue-outer": continue outer; } } @@ -56355,9 +56479,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_8 = _loop_22(combination); - if (typeof state_8 === "object") - return state_8.value; + var state_7 = _loop_21(combination); + if (typeof state_7 === "object") + return state_7.value; } var result = -1; for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) { @@ -56441,7 +56565,7 @@ var ts; } return 0; } - if (!skipOptional && sourceProp.flags & 16777216 && !(targetProp.flags & 16777216)) { + if (!skipOptional && sourceProp.flags & 16777216 && targetProp.flags & 106500 && !(targetProp.flags & 16777216)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -56999,7 +57123,7 @@ var ts; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes", "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); links.variances = ts.emptyArray; var variances = []; - var _loop_24 = function (tp) { + var _loop_23 = function (tp) { var modifiers = getVarianceModifiers(tp); var variance = modifiers & 65536 ? modifiers & 32768 ? 0 : 1 : @@ -57030,7 +57154,7 @@ var ts; }; for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var tp = typeParameters_2[_i]; - _loop_24(tp); + _loop_23(tp); } links.variances = variances; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); @@ -57412,8 +57536,7 @@ var ts; return !!(type.flags & 109440); } function isUnitLikeType(type) { - return type.flags & 2097152 ? ts.some(type.types, isUnitType) : - !!(type.flags & 109440); + return isUnitType(getBaseConstraintOrType(type)); } function extractUnitType(type) { return type.flags & 2097152 ? ts.find(type.types, isUnitType) || type : type; @@ -58178,7 +58301,7 @@ var ts; && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); } function isMemberOfStringMapping(source, target) { - if (target.flags & (4 | 3)) { + if (target.flags & (4 | 1)) { return true; } if (target.flags & 134217728) { @@ -58675,7 +58798,7 @@ var ts; var matches = inferTypesFromTemplateLiteralType(source, target); var types = target.types; if (matches || ts.every(target.texts, function (s) { return s.length === 0; })) { - var _loop_25 = function (i) { + var _loop_24 = function (i) { var source_1 = matches ? matches[i] : neverType; var target_3 = types[i]; if (source_1.flags & 128 && target_3.flags & 8650752) { @@ -58719,7 +58842,7 @@ var ts; inferFromTypes(source_1, target_3); }; for (var i = 0; i < types.length; i++) { - _loop_25(i); + _loop_24(i); } } } @@ -59126,7 +59249,7 @@ var ts; } if (ts.isEntityNameExpression(node.argumentExpression)) { var symbol = resolveEntityName(node.argumentExpression, 111551, true); - if (!symbol || !isConstVariable(symbol)) + if (!symbol || !(isConstVariable(symbol) || (symbol.flags & 8))) return undefined; var declaration = symbol.valueDeclaration; if (declaration === undefined) @@ -59140,7 +59263,12 @@ var ts; } if (ts.hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node.argumentExpression)) { var initializer = ts.getEffectiveInitializer(declaration); - return initializer && tryGetNameFromType(getTypeOfExpression(initializer)); + if (initializer) { + return tryGetNameFromType(getTypeOfExpression(initializer)); + } + if (ts.isEnumMember(declaration)) { + return ts.getTextOfPropertyName(declaration.name); + } } } return undefined; @@ -59194,7 +59322,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_26 = function (type) { + var _loop_25 = function (type) { if (type.flags & (524288 | 2097152 | 58982400)) { var discriminant = getTypeOfPropertyOfType(type, name); if (discriminant) { @@ -59220,9 +59348,9 @@ var ts; }; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var type = types_15[_i]; - var state_10 = _loop_26(type); - if (typeof state_10 === "object") - return state_10.value; + var state_9 = _loop_25(type); + if (typeof state_9 === "object") + return state_9.value; } return count >= 10 && count * 2 >= types.length ? map : undefined; } @@ -59770,6 +59898,7 @@ var ts; ts.isInJSFile(node) && ts.hasInitializer(node) && node.initializer && ts.isFunctionExpressionOrArrowFunction(node.initializer) && ts.getEffectiveReturnTypeNode(node.initializer)); } function getExplicitTypeOfSymbol(symbol, diagnostic) { + symbol = resolveSymbol(symbol); if (symbol.flags & (16 | 8192 | 32 | 512)) { return getTypeOfSymbol(symbol); } @@ -59804,7 +59933,7 @@ var ts; switch (node.kind) { case 79: var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); - return getExplicitTypeOfSymbol(symbol.flags & 2097152 ? resolveAlias(symbol) : symbol, diagnostic); + return getExplicitTypeOfSymbol(symbol, diagnostic); case 108: return getExplicitThisType(node); case 106: @@ -60243,7 +60372,7 @@ var ts; type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (expr.kind === 218 && isMatchingReference(reference, expr.expression)) { - type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { if (strictNullChecks) { @@ -60476,7 +60605,7 @@ var ts; !!(prop.flags & 16777216) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue; } - function narrowByInKeyword(type, nameType, assumeTrue) { + function narrowTypeByInKeyword(type, nameType, assumeTrue) { var name = getPropertyNameFromType(nameType); var isKnownProperty = someType(type, function (t) { return isTypePresencePossible(t, name, true); }); if (isKnownProperty) { @@ -60553,7 +60682,7 @@ var ts; return getTypeWithFacts(type, assumeTrue ? 524288 : 65536); } if (isMatchingReference(reference, target)) { - return narrowByInKeyword(type, leftType, assumeTrue); + return narrowTypeByInKeyword(type, leftType, assumeTrue); } } break; @@ -60715,7 +60844,7 @@ var ts; neverType; }); } - function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + function narrowTypeBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!witnesses) { return type; @@ -61042,12 +61171,12 @@ var ts; }); } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, 111551) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, 111551) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551)) { var target = resolveAlias(symbol); - if (target.flags & 111551) { + if (getAllSymbolFlags(target) & (111551 | 1048576)) { if (compilerOptions.isolatedModules || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || - !isConstEnumOrConstEnumOnlyModule(target)) { + !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -61209,7 +61338,7 @@ var ts; (isConstVariable(localOrExportSymbol) && type !== autoArrayType || isParameter && !isSymbolAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 | 16384)) !== 0 || isInTypeQuery(node) || node.parent.kind === 278) || node.parent.kind === 232 || @@ -61234,6 +61363,12 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function isSameScopedBindingElement(node, declaration) { + if (ts.isBindingElement(declaration)) { + var bindingElement = ts.findAncestor(node, ts.isBindingElement); + return bindingElement && ts.getRootDeclaration(bindingElement) === ts.getRootDeclaration(declaration); + } + } function shouldMarkIdentifierAliasReferenced(node) { var _a; var parent = node.parent; @@ -61532,11 +61667,16 @@ var ts; var immediateContainer = ts.getSuperContainer(node, true); var container = immediateContainer; var needToCaptureLexicalThis = false; + var inAsyncFunction = false; if (!isCallExpression) { while (container && container.kind === 216) { + if (ts.hasSyntacticModifier(container, 512)) + inAsyncFunction = true; container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = languageVersion < 2; } + if (container && ts.hasSyntacticModifier(container, 512)) + inAsyncFunction = true; } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; @@ -61575,7 +61715,7 @@ var ts; nodeCheckFlag = 256; } getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 171 && ts.hasSyntacticModifier(container, 512)) { + if (container.kind === 171 && inAsyncFunction) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096; } @@ -62195,7 +62335,7 @@ var ts; function instantiateContextualType(contextualType, node, contextFlags) { if (contextualType && maybeTypeOfKind(contextualType, 465829888)) { var inferenceContext = getInferenceContext(node); - if (inferenceContext && contextFlags & 1 && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + if (inferenceContext && contextFlags & 1 && ts.some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) { return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); } if (inferenceContext === null || inferenceContext === void 0 ? void 0 : inferenceContext.returnMapper) { @@ -64724,7 +64864,7 @@ var ts; var spreadIndex = getSpreadArgumentIndex(args); if (spreadIndex >= 0) { var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_27 = function (i) { + var _loop_26 = function (i) { var arg = args[i]; var spreadType = arg.kind === 227 && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { @@ -64740,7 +64880,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_27(i); + _loop_26(i); } return effectiveArgs_1; } @@ -64990,7 +65130,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_28 = function (c) { + var _loop_27 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0, true, chain_2); if (diags_2) { @@ -65008,7 +65148,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_28(c); + _loop_27(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -65151,7 +65291,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_29 = function (i) { + var _loop_28 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -65159,7 +65299,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_29(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0; @@ -65994,7 +66134,7 @@ var ts; if (symbol && symbol.flags & 2097152) { symbol = resolveAlias(symbol); } - return !!(symbol && (symbol.flags & 384) && getEnumKind(symbol) === 1); + return !!(symbol && (getAllSymbolFlags(symbol) & 384) && getEnumKind(symbol) === 1); } return false; } @@ -66619,7 +66759,17 @@ var ts; } function isExhaustiveSwitchStatement(node) { var links = getNodeLinks(node); - return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); + if (links.isExhaustive === undefined) { + links.isExhaustive = 0; + var exhaustive = computeExhaustiveSwitchStatement(node); + if (links.isExhaustive === 0) { + links.isExhaustive = exhaustive; + } + } + else if (links.isExhaustive === 0) { + links.isExhaustive = false; + } + return links.isExhaustive; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 218) { @@ -66627,14 +66777,14 @@ var ts; if (!witnesses) { return false; } - var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(node.expression.expression)); + var operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression)); var notEqualFacts_2 = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); if (operandConstraint.flags & 3) { return (556800 & notEqualFacts_2) === 556800; } return !someType(operandConstraint, function (t) { return (getTypeFacts(t) & notEqualFacts_2) === notEqualFacts_2; }); } - var type = getTypeOfExpression(node.expression); + var type = checkExpressionCached(node.expression); if (!isLiteralType(type)) { return false; } @@ -68144,6 +68294,9 @@ var ts; function hasInferenceCandidates(info) { return !!(info.candidates || info.contraCandidates); } + function hasInferenceCandidatesOrDefault(info) { + return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter)); + } function hasOverlappingInferences(a, b) { for (var i = 0; i < a.length; i++) { if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) { @@ -68776,7 +68929,7 @@ var ts; var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var indexSignatureMap_1 = new ts.Map(); - var _loop_30 = function (declaration) { + var _loop_29 = function (declaration) { if (declaration.parameters.length === 1 && declaration.parameters[0].type) { forEachType(getTypeFromTypeNode(declaration.parameters[0].type), function (type) { var entry = indexSignatureMap_1.get(getTypeId(type)); @@ -68791,7 +68944,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_30(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -69037,7 +69190,7 @@ var ts; } var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { - if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 268435456); })) { + if (ts.some(symbol.declarations, function (d) { return ts.isTypeDeclaration(d) && !!(d.flags & 268435456); })) { addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 && symbol.flags & 8) { @@ -69571,7 +69724,7 @@ var ts; if (isReferenceToType(type, getGlobalPromiseType(false))) { return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; } - if (allTypesAssignableToKind(type, 131068 | 131072)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 | 131072)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(type, "then"); @@ -69627,7 +69780,7 @@ var ts; return awaitedType || errorType; } function isThenableType(type) { - if (allTypesAssignableToKind(type, 131068 | 131072)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 | 131072)) { return false; } var thenFunction = getTypeOfPropertyOfType(type, "then"); @@ -69653,7 +69806,7 @@ var ts; if (isGenericObjectType(type)) { var baseConstraint = getBaseConstraintOfType(type); if (baseConstraint ? - baseConstraint.flags & 3 || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint) : + baseConstraint.flags & 3 || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : maybeTypeOfKind(type, 8650752)) { return true; } @@ -70158,7 +70311,7 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + var message = ts.isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(declaration, 0, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { @@ -71335,7 +71488,13 @@ var ts; var message = allowAsyncIterables ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; - return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + var suggestAwait = !!getAwaitedTypeOfPromise(type) + || (!allowAsyncIterables && + ts.isForOfStatement(errorNode.parent) && + errorNode.parent.expression === errorNode && + getGlobalAsyncIterableType(false) !== emptyGenericType && + isTypeAssignableTo(type, getGlobalAsyncIterableType(false))); + return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) { return getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, false); @@ -71731,7 +71890,7 @@ var ts; var propDeclaration = declaration && declaration.kind === 223 || name && name.kind === 164 ? declaration : undefined; var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_31 = function (info) { + var _loop_30 = function (info) { var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; var errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !ts.some(getBaseTypes(type), function (base) { return !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType); }) ? interfaceDeclaration : undefined); @@ -71745,7 +71904,7 @@ var ts; }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_31(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -71753,7 +71912,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 ? ts.getDeclarationOfKind(type.symbol, 261) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_32 = function (info) { + var _loop_31 = function (info) { if (info === checkInfo) return "continue"; var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; @@ -71765,7 +71924,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_32(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -71815,7 +71974,7 @@ var ts; } else { ts.forEach(jsdocParameters, function (_a, index) { - var name = _a.name; + var name = _a.name, isNameFirst = _a.isNameFirst; if (excludedParameters.has(index) || ts.isIdentifier(name) && parameters.has(name.escapedText)) { return; } @@ -71825,7 +71984,9 @@ var ts; } } else { - errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + if (!isNameFirst) { + errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + } } }); } @@ -72060,7 +72221,7 @@ var ts; 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 _loop_33 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -72075,7 +72236,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_33(member); + _loop_32(member); } } function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors) { @@ -72150,7 +72311,7 @@ var ts; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_34 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -72168,7 +72329,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_34(member); + _loop_33(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -72215,7 +72376,7 @@ var ts; function checkKindsOfPropertyMemberOverrides(type, baseType) { var _a, _b, _c, _d; var baseProperties = getPropertiesOfType(baseType); - var _loop_35 = function (baseProperty) { + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304) { return "continue"; @@ -72313,8 +72474,8 @@ var ts; }; basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { var baseProperty = baseProperties_1[_i]; - var state_11 = _loop_35(baseProperty); - switch (state_11) { + var state_10 = _loop_34(baseProperty); + switch (state_10) { case "continue-basePropertyCheck": continue basePropertyCheck; } } @@ -72800,11 +72961,10 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { - var _a; switch (node.kind) { case 240: - for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { - var decl = _b[_i]; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; @@ -72820,8 +72980,8 @@ var ts; case 257: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { - var el = _d[_c]; + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } break; @@ -72835,13 +72995,6 @@ var ts; if (isGlobalAugmentation) { return; } - var symbol = getSymbolOfNode(node); - if (symbol) { - var reportError = !(symbol.flags & 33554432); - if (!reportError) { - reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } break; } } @@ -72929,10 +73082,11 @@ var ts; } return; } + var targetFlags = getAllSymbolFlags(target); var excludedMeanings = (symbol.flags & (111551 | 1048576) ? 111551 : 0) | (symbol.flags & 788968 ? 788968 : 0) | (symbol.flags & 1920 ? 1920 : 0); - if (target.flags & excludedMeanings) { + if (targetFlags & excludedMeanings) { var message = node.kind === 278 ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; @@ -72942,7 +73096,7 @@ var ts; && !ts.isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 16777216)) { var typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol); - var isType = !(target.flags & 111551); + var isType = !(targetFlags & 111551); if (isType || typeOnlyAlias) { switch (node.kind) { case 270: @@ -73096,13 +73250,14 @@ var ts; if (node.moduleReference.kind !== 280) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 111551) { + var targetFlags = getAllSymbolFlags(target); + if (targetFlags & 111551) { var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 | 1920).flags & 1920)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 788968) { + if (targetFlags & 788968) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -73229,7 +73384,7 @@ var ts; markExportAsReferenced(node); } var target = symbol && (symbol.flags & 2097152 ? resolveAlias(symbol) : symbol); - if (!target || target === unknownSymbol || target.flags & 111551) { + if (!target || getAllSymbolFlags(target) & 111551) { checkExpressionCached(node.propertyName || node.name); } } @@ -73273,7 +73428,7 @@ var ts; if (sym) { markAliasReferenced(sym, id); var target = sym.flags & 2097152 ? resolveAlias(sym) : sym; - if (target === unknownSymbol || target.flags & 111551) { + if (getAllSymbolFlags(target) & 111551) { checkExpressionCached(node.expression); } } @@ -73870,29 +74025,9 @@ var ts; } function isTypeDeclarationName(name) { return name.kind === 79 && - isTypeDeclaration(name.parent) && + ts.isTypeDeclaration(name.parent) && ts.getNameOfDeclaration(name.parent) === name; } - function isTypeDeclaration(node) { - switch (node.kind) { - case 165: - case 260: - case 261: - case 262: - case 263: - case 348: - case 341: - case 342: - return true; - case 270: - return node.isTypeOnly; - case 273: - case 278: - return node.parent.parent.isTypeOnly; - default: - return false; - } - } function isTypeReferenceIdentifier(node) { while (node.parent.kind === 163) { node = node.parent; @@ -74287,7 +74422,7 @@ var ts; var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } - if (isTypeDeclaration(node)) { + if (ts.isTypeDeclaration(node)) { var symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); } @@ -74445,7 +74580,7 @@ var ts; return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 111551); + return s && !!(getAllSymbolFlags(s) & 111551); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -74484,7 +74619,7 @@ var ts; var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueOrAliasSymbol(node); - if (isNonLocalAlias(symbol, 111551) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, 111551) && !getTypeOnlyAliasDeclaration(symbol, 111551)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -74551,7 +74686,7 @@ var ts; case 273: case 278: var symbol = getSymbolOfNode(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); + return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551); case 275: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || @@ -74572,6 +74707,7 @@ var ts; return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); } function isAliasResolvedToValue(symbol) { + var _a; if (!symbol) { return false; } @@ -74579,7 +74715,7 @@ var ts; if (target === unknownSymbol) { return true; } - return !!(target.flags & 111551) && + return !!(((_a = getAllSymbolFlags(target)) !== null && _a !== void 0 ? _a : -1) & 111551) && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -74594,7 +74730,7 @@ var ts; } var target = getSymbolLinks(symbol).aliasTarget; if (target && ts.getEffectiveModifierFlags(node) & 1 && - target.flags & 111551 && + getAllSymbolFlags(target) & 111551 && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { return true; } @@ -82400,8 +82536,11 @@ var ts; } return ts.visitEachChild(node, visitor, context); case 174: + return doWithContext(1 | 2, visitGetAccessorDeclaration, node); case 175: + return doWithContext(1 | 2, visitSetAccessorDeclaration, node); case 173: + return doWithContext(1 | 2, visitConstructorDeclaration, node); case 260: case 228: return doWithContext(1 | 2, visitDefault, node); @@ -82492,10 +82631,19 @@ var ts; } return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); + } function visitMethodDeclaration(node) { return factory.updateMethodDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 ? transformAsyncFunctionBody(node) - : ts.visitFunctionBody(node.body, visitor, context)); + : transformMethodBody(node)); + } + function visitGetAccessorDeclaration(node) { + return factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), undefined, transformMethodBody(node)); + } + function visitSetAccessorDeclaration(node) { + return factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); } function visitFunctionDeclaration(node) { return factory.updateFunctionDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.getFunctionFlags(node) & 2 @@ -82579,6 +82727,39 @@ var ts; } return false; } + function transformMethodBody(node) { + ts.Debug.assertIsDefined(node.body); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = new ts.Set(); + hasSuperElementAccess = false; + var updated = ts.visitFunctionBody(node.body, visitor, context); + var originalMethod = ts.getOriginalNode(node, ts.isFunctionLikeDeclaration); + var emitSuperHelpers = languageVersion >= 2 && + resolver.getNodeCheckFlags(node) & (4096 | 2048) && + (ts.getFunctionFlags(originalMethod) & 3) !== 3; + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + if (capturedSuperProperties.size) { + var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + var statements = updated.statements.slice(); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + updated = factory.updateBlock(updated, statements); + } + if (hasSuperElementAccess) { + if (resolver.getNodeCheckFlags(node) & 4096) { + ts.addEmitHelper(updated, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048) { + ts.addEmitHelper(updated, ts.asyncSuperHelper); + } + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return updated; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -83132,11 +83313,22 @@ var ts; } return node; } - function convertForOfStatementHead(node, boundValue) { - var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue); + function convertForOfStatementHead(node, boundValue, nonUserCode) { + var value = factory.createTempVariable(hoistVariableDeclaration); + var iteratorValueExpression = factory.createAssignment(value, boundValue); + var iteratorValueStatement = factory.createExpressionStatement(iteratorValueExpression); + ts.setSourceMapRange(iteratorValueStatement, node.expression); + var exitNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createFalse()); + var exitNonUserCodeStatement = factory.createExpressionStatement(exitNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var enterNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createTrue()); + var enterNonUserCodeStatement = factory.createExpressionStatement(enterNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var statements = []; + var binding = ts.createForOfBindingStatement(factory, node.initializer, value); + statements.push(ts.visitNode(binding, visitor, ts.isStatement)); var bodyLocation; var statementsLocation; - var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); @@ -83146,7 +83338,14 @@ var ts; else { statements.push(statement); } - return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); + var body = ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); + return factory.createBlock([ + iteratorValueStatement, + exitNonUserCodeStatement, + factory.createTryStatement(body, undefined, factory.createBlock([ + enterNonUserCodeStatement + ])) + ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 @@ -83157,6 +83356,8 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(undefined); var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(undefined); + var nonUserCode = factory.createTempVariable(undefined); + var done = factory.createTempVariable(hoistVariableDeclaration); var errorRecord = factory.createUniqueName("e"); var catchVariable = factory.getGeneratedNameForNode(errorRecord); var returnMethod = factory.createTempVariable(undefined); @@ -83171,9 +83372,14 @@ var ts; factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), callValues]) : callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([ + factory.createVariableDeclaration(nonUserCode, undefined, undefined, factory.createTrue()), ts.setTextRange(factory.createVariableDeclaration(iterator, undefined, undefined, initializer), node.expression), factory.createVariableDeclaration(result) - ]), node.expression), 2097152), factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, getValue)), node), 256); + ]), node.expression), 2097152), factory.inlineExpressions([ + factory.createAssignment(result, createDownlevelAwait(callNext)), + factory.createAssignment(done, getDone), + factory.createLogicalNot(done) + ]), undefined, convertForOfStatementHead(node, getValue, nonUserCode)), node), 256); ts.setOriginalNode(forStatement, node); return factory.createTryStatement(factory.createBlock([ factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -83183,7 +83389,7 @@ var ts; ]))) ]), 1)), factory.createBlock([ factory.createTryStatement(factory.createBlock([ - ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(getDone)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1) + ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(factory.createLogicalNot(nonUserCode), factory.createLogicalNot(done)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1) ]), undefined, ts.setEmitFlags(factory.createBlock([ ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1) ]), 1)) @@ -84747,11 +84953,13 @@ var ts; return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); } function visitIdentifier(node) { - if (!convertedLoopState) { - return node; + if (convertedLoopState) { + if (resolver.isArgumentsLocalBinding(node)) { + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + } } - if (resolver.isArgumentsLocalBinding(node)) { - return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + if (node.hasExtendedUnicodeEscape) { + return ts.setOriginalNode(ts.setTextRange(factory.createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText)), node), node); } return node; } @@ -87283,19 +87491,23 @@ var ts; } function transformAndEmitForInStatement(node) { if (containsYield(node)) { + var obj = declareLocal(); var keysArray = declareLocal(); var key = declareLocal(); var keysIndex = factory.createLoopVariable(); var initializer = node.initializer; hoistVariableDeclaration(keysIndex); + emitAssignment(obj, ts.visitNode(node.expression, visitor, ts.isExpression)); emitAssignment(keysArray, factory.createArrayLiteralExpression()); - emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), undefined, [key])))); + emitStatement(factory.createForInStatement(key, obj, factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), undefined, [key])))); emitAssignment(keysIndex, factory.createNumericLiteral(0)); var conditionLabel = defineLabel(); var incrementLabel = defineLabel(); - var endLabel = beginLoopBlock(incrementLabel); + var endLoopLabel = beginLoopBlock(incrementLabel); markLabel(conditionLabel); - emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitBreakWhenFalse(endLoopLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitAssignment(key, factory.createElementAccessExpression(keysArray, keysIndex)); + emitBreakWhenFalse(incrementLabel, factory.createBinaryExpression(key, 101, obj)); var variable = void 0; if (ts.isVariableDeclarationList(initializer)) { for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { @@ -87308,7 +87520,7 @@ var ts; variable = ts.visitNode(initializer, visitor, ts.isExpression); ts.Debug.assert(ts.isLeftHandSideExpression(variable)); } - emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex)); + emitAssignment(variable, key); transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex))); @@ -88588,18 +88800,18 @@ var ts; return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return createImportCallExpressionCommonJS(argument, containsLexicalThis); + return createImportCallExpressionCommonJS(argument); } } function createImportCallExpressionUMD(arg, containsLexicalThis) { needUMDDynamicImportHelper = true; if (ts.isSimpleCopiableExpression(arg)) { var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? factory.createStringLiteralFromNode(arg) : ts.setEmitFlags(ts.setTextRange(factory.cloneNode(arg), arg), 1536); - return factory.createConditionalExpression(factory.createIdentifier("__syncRequire"), undefined, createImportCallExpressionCommonJS(arg, containsLexicalThis), undefined, createImportCallExpressionAMD(argClone, containsLexicalThis)); + return factory.createConditionalExpression(factory.createIdentifier("__syncRequire"), undefined, createImportCallExpressionCommonJS(arg), undefined, createImportCallExpressionAMD(argClone, containsLexicalThis)); } else { var temp = factory.createTempVariable(hoistVariableDeclaration); - return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression(factory.createIdentifier("__syncRequire"), undefined, createImportCallExpressionCommonJS(temp, containsLexicalThis), undefined, createImportCallExpressionAMD(temp, containsLexicalThis))); + return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression(factory.createIdentifier("__syncRequire"), undefined, createImportCallExpressionCommonJS(temp, true), undefined, createImportCallExpressionAMD(temp, containsLexicalThis))); } } function createImportCallExpressionAMD(arg, containsLexicalThis) { @@ -88628,9 +88840,10 @@ var ts; } return promise; } - function createImportCallExpressionCommonJS(arg, containsLexicalThis) { + function createImportCallExpressionCommonJS(arg, isInlineable) { + var temp = arg && !ts.isSimpleInlineableExpression(arg) && !isInlineable ? factory.createTempVariable(hoistVariableDeclaration) : undefined; var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), undefined, []); - var requireCall = factory.createCallExpression(factory.createIdentifier("require"), undefined, arg ? [arg] : []); + var requireCall = factory.createCallExpression(factory.createIdentifier("require"), undefined, temp ? [temp] : arg ? [arg] : []); if (ts.getESModuleInterop(compilerOptions)) { requireCall = emitHelpers().createImportStarHelper(requireCall); } @@ -88640,11 +88853,9 @@ var ts; } else { func = factory.createFunctionExpression(undefined, undefined, undefined, undefined, [], undefined, factory.createBlock([factory.createReturnStatement(requireCall)])); - if (containsLexicalThis) { - ts.setEmitFlags(func, 8); - } } - return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), undefined, [func]); + var downleveledImport = factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), undefined, [func]); + return temp === undefined ? downleveledImport : factory.createCommaListExpression([factory.createAssignment(temp, arg), downleveledImport]); } function getHelperExpressionForExport(node, innerExpr) { if (!ts.getESModuleInterop(compilerOptions) || ts.getEmitFlags(node) & 67108864) { @@ -101566,7 +101777,7 @@ var ts; var canCopyEmitSignatures = compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && !outFilePath && - !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); if (useOldState) { (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); if (!outFilePath && oldState.affectedFilesPendingEmit) { @@ -102588,7 +102799,7 @@ var ts; var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47; if (isNonDirectorySeparatorRoot && dirPath.search(/[a-zA-Z]:/) !== 0 && - pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { + pathPartForUserCheck.search(/[a-zA-Z]\$\//) === 0) { nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1); if (nextDirectorySeparator === -1) { return false; @@ -103678,7 +103889,7 @@ var ts; importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules; }); var sortedPaths = []; - var _loop_36 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -103702,9 +103913,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_12 = _loop_36(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_12 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -103763,7 +103974,7 @@ var ts; } function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - var _loop_37 = function (patternText_1) { + var _loop_36 = function (patternText_1) { var pattern = ts.normalizePath(patternText_1); var indexOfStar = pattern.indexOf("*"); var candidates = allowedEndings.map(function (ending) { return ({ @@ -103794,9 +104005,9 @@ var ts; }; for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { var patternText_1 = _a[_i]; - var state_13 = _loop_37(patternText_1); - if (typeof state_13 === "object") - return state_13.value; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } function validateEnding(_a) { @@ -103865,15 +104076,21 @@ var ts; return undefined; } function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { + var normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPaths === undefined) { + return undefined; + } + var normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePaths = ts.flatMap(normalizedSourcePaths, function (sourcePath) { + return ts.map(normalizedTargetPaths, function (targetPath) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName)); }); + }); + var shortest = ts.min(relativePaths, ts.compareNumberOfDirectorySeparators); + if (!shortest) { return undefined; } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs - ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions) - : ts.removeFileExtension(relativePath); + ? removeExtensionAndIndexPostFix(shortest, ending, compilerOptions) + : ts.removeFileExtension(shortest); } function tryGetModuleNameAsNodeModule(_a, _b, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { var path = _a.path, isRedirect = _a.isRedirect; @@ -103993,8 +104210,8 @@ var ts; } } } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { + function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.mapDefined(rootDirs, function (rootDir) { var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath; }); @@ -106380,7 +106597,9 @@ var ts; } if (buildInfo.program) { if (((_a = buildInfo.program.changeFileSet) === null || _a === void 0 ? void 0 : _a.length) || - (!project.options.noEmit && ((_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length))) { + (!project.options.noEmit ? + (_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length : + ts.some(buildInfo.program.semanticDiagnosticsPerFile, ts.isArray))) { return { type: ts.UpToDateStatusType.OutOfDateBuildInfo, buildInfoFile: buildInfoPath diff --git a/lib/tsserver.js b/lib/tsserver.js index 5d1d55532dede..444cf2ffb3504 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -109,7 +109,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 = "".concat(ts.versionMajorMinor, ".1-beta"); + ts.version = "".concat(ts.versionMajorMinor, ".2-rc"); /* @internal */ var Comparison; (function (Comparison) { @@ -1901,8 +1901,8 @@ var ts; return compareValues(a === null || a === void 0 ? void 0 : a.start, b === null || b === void 0 ? void 0 : b.start) || compareValues(a === null || a === void 0 ? void 0 : a.length, b === null || b === void 0 ? void 0 : b.length); } ts.compareTextSpans = compareTextSpans; - function min(a, b, compare) { - return compare(a, b) === -1 /* Comparison.LessThan */ ? a : b; + function min(items, compare) { + return reduceLeft(items, function (x, y) { return compare(x, y) === -1 /* Comparison.LessThan */ ? x : y; }); } ts.min = min; /** @@ -3215,11 +3215,13 @@ var ts; // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers // > MUST NOT include leading zeroes. var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; // https://semver.org/#spec-item-10 // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated // > identifiers immediately following the patch or pre-release version. Identifiers MUST // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var buildPartRegExp = /^[a-z0-9-]+$/i; // https://semver.org/#spec-item-9 // > Numeric identifiers MUST NOT include leading zeroes. var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; @@ -3239,13 +3241,15 @@ var ts; ts.Debug.assert(major >= 0, "Invalid argument: major"); ts.Debug.assert(minor >= 0, "Invalid argument: minor"); ts.Debug.assert(patch >= 0, "Invalid argument: patch"); - ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); - ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + var prereleaseArray = prerelease ? ts.isArray(prerelease) ? prerelease : prerelease.split(".") : ts.emptyArray; + var buildArray = build ? ts.isArray(build) ? build : build.split(".") : ts.emptyArray; + ts.Debug.assert(ts.every(prereleaseArray, function (s) { return prereleasePartRegExp.test(s); }), "Invalid argument: prerelease"); + ts.Debug.assert(ts.every(buildArray, function (s) { return buildPartRegExp.test(s); }), "Invalid argument: build"); this.major = major; this.minor = minor; this.patch = patch; - this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; - this.build = build ? build.split(".") : ts.emptyArray; + this.prerelease = prereleaseArray; + this.build = buildArray; } Version.tryParse = function (text) { var result = tryParseComponents(text); @@ -3284,6 +3288,10 @@ var ts; default: return ts.Debug.assertNever(field); } }; + Version.prototype.with = function (fields) { + var _a = fields.major, major = _a === void 0 ? this.major : _a, _b = fields.minor, minor = _b === void 0 ? this.minor : _b, _c = fields.patch, patch = _c === void 0 ? this.patch : _c, _d = fields.prerelease, prerelease = _d === void 0 ? this.prerelease : _d, _e = fields.build, build = _e === void 0 ? this.build : _e; + return new Version(major, minor, patch, prerelease, build); + }; Version.prototype.toString = function () { var result = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); if (ts.some(this.prerelease)) @@ -3292,7 +3300,7 @@ var ts; result += "+".concat(this.build.join(".")); return result; }; - Version.zero = new Version(0, 0, 0); + Version.zero = new Version(0, 0, 0, ["0"]); return Version; }()); ts.Version = Version; @@ -3375,6 +3383,10 @@ var ts; } return undefined; }; + /** + * Tests whether a version matches the range. This is equivalent to `satisfies(version, range, { includePrerelease: true })`. + * in `node-semver`. + */ VersionRange.prototype.test = function (version) { if (typeof version === "string") version = new Version(version); @@ -3485,19 +3497,20 @@ var ts; break; case "<": case ">=": - comparators.push(createComparator(operator, version)); + comparators.push(isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version.with({ prerelease: "0" })) : + createComparator(operator, version)); break; case "<=": case ">": - comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : - isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major").with({ prerelease: "0" })) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor").with({ prerelease: "0" })) : createComparator(operator, version)); break; case "=": case undefined: if (isWildcard(minor) || isWildcard(patch)) { - comparators.push(createComparator(">=", version)); - comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + comparators.push(createComparator(">=", version.with({ prerelease: "0" }))); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor").with({ prerelease: "0" }))); } else { comparators.push(createComparator("=", version)); @@ -5106,8 +5119,8 @@ var ts; NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAccessInAsync"] = 2048] = "MethodWithSuperPropertyAccessInAsync"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAssignmentInAsync"] = 4096] = "MethodWithSuperPropertyAssignmentInAsync"; NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; @@ -6742,7 +6755,7 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; + var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; var pollingWatches = new ts.Map(); var fsWatches = new ts.Map(); var fsWatchesRecursive = new ts.Map(); @@ -6808,8 +6821,8 @@ var ts; return useNonPollingWatchers ? // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : - // Default to do not use fixed polling interval - { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.UseFsEvents }; + // Default to using fs events + { watchFile: ts.WatchFileKind.UseFsEvents }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -7081,7 +7094,6 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, - defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, inodeWatching: isLinuxOrMacOs, sysLog: sysLog, }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; @@ -9592,6 +9604,10 @@ var ts; Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted: diag(6399, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399", "Project '{0}' is out of date because buildinfo file '{1}' indicates that some of the changes were not emitted"), Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files: diag(6400, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400", "Project '{0}' is up to date but needs to update timestamps of output files that are older than input files"), Project_0_is_out_of_date_because_there_was_error_reading_file_1: diag(6401, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401", "Project '{0}' is out of date because there was error reading file '{1}'"), + Resolving_in_0_mode_with_conditions_1: diag(6402, ts.DiagnosticCategory.Message, "Resolving_in_0_mode_with_conditions_1_6402", "Resolving in {0} mode with conditions {1}."), + Matched_0_condition_1: diag(6403, ts.DiagnosticCategory.Message, "Matched_0_condition_1_6403", "Matched '{0}' condition '{1}'."), + Using_0_subpath_1_with_target_2: diag(6404, ts.DiagnosticCategory.Message, "Using_0_subpath_1_with_target_2_6404", "Using '{0}' subpath '{1}' with target '{2}'."), + Saw_non_matching_condition_0: diag(6405, ts.DiagnosticCategory.Message, "Saw_non_matching_condition_0_6405", "Saw non-matching condition '{0}'."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -9908,6 +9924,8 @@ var ts; Remove_type_from_import_of_0_from_1: diag(90056, ts.DiagnosticCategory.Message, "Remove_type_from_import_of_0_from_1_90056", "Remove 'type' from import of '{0}' from \"{1}\""), Add_import_from_0: diag(90057, ts.DiagnosticCategory.Message, "Add_import_from_0_90057", "Add import from \"{0}\""), Update_import_from_0: diag(90058, ts.DiagnosticCategory.Message, "Update_import_from_0_90058", "Update import from \"{0}\""), + Export_0_from_module_1: diag(90059, ts.DiagnosticCategory.Message, "Export_0_from_module_1_90059", "Export '{0}' from module '{1}'"), + Export_all_referenced_locals: diag(90060, ts.DiagnosticCategory.Message, "Export_all_referenced_locals_90060", "Export all referenced locals"), 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}"), @@ -11365,7 +11383,7 @@ var ts; return -1; } function peekExtendedUnicodeEscape() { - if (languageVersion >= 2 /* ScriptTarget.ES2015 */ && codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { + if (codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { var start_2 = pos; pos += 3; var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); @@ -21668,6 +21686,32 @@ var ts; return parameter.kind === 343 /* SyntaxKind.JSDocParameterTag */ ? (_a = parameter.typeExpression) === null || _a === void 0 ? void 0 : _a.type : parameter.type; } ts.getParameterTypeNode = getParameterTypeNode; + function isTypeDeclaration(node) { + switch (node.kind) { + case 165 /* SyntaxKind.TypeParameter */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: + return true; + case 270 /* SyntaxKind.ImportClause */: + return node.isTypeOnly; + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: + return node.parent.parent.isTypeOnly; + default: + return false; + } + } + ts.isTypeDeclaration = isTypeDeclaration; + function canHaveExportModifier(node) { + return ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) || isTypeDeclaration(node) || (ts.isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node)); + } + ts.canHaveExportModifier = canHaveExportModifier; })(ts || (ts = {})); /* @internal */ var ts; @@ -21676,13 +21720,11 @@ var ts; * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator. */ function createBaseNodeFactory() { - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name return { createBaseSourceFileNode: createBaseSourceFileNode, createBaseIdentifierNode: createBaseIdentifierNode, @@ -23146,7 +23188,7 @@ var ts; return node; } // @api - function createIdentifier(text, typeArguments, originalKeywordKind) { + function createIdentifier(text, typeArguments, originalKeywordKind, hasExtendedUnicodeEscape) { var node = createBaseIdentifier(text, originalKeywordKind); if (typeArguments) { // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations @@ -23155,6 +23197,10 @@ var ts; if (node.originalKeywordKind === 133 /* SyntaxKind.AwaitKeyword */) { node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } + if (hasExtendedUnicodeEscape) { + node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + } return node; } // @api @@ -27610,11 +27656,9 @@ var ts; rawTextScanner.setText("`" + rawText + "`"); break; case 15 /* SyntaxKind.TemplateHead */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("`" + rawText + "${"); break; case 16 /* SyntaxKind.TemplateMiddle */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("}" + rawText + "${"); break; case 17 /* SyntaxKind.TemplateTail */: @@ -27973,7 +28017,6 @@ var ts; return node; } ts.createInputFiles = createInputFiles; - // tslint:disable-next-line variable-name var SourceMapSource; /** * Create an external source map source file reference @@ -28765,6 +28808,8 @@ var ts; // - The verb (`next`, `throw`, or `return` method) to delegate to the expression // of a `yield*`. // - The result of evaluating the verb delegated to the expression of a `yield*`. + // g A temporary variable that holds onto the generator object until the generator + // is started, allowing it to also act as the `suspendedStart` state. // // functions: // verb(n) Creates a bound callback to the `step` function for opcode `n`. @@ -28803,7 +28848,7 @@ var ts; importName: "__generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; // ES Module Helpers ts.createBindingHelper = { @@ -32107,13 +32152,11 @@ var ts; var scanner = ts.createScanner(99 /* ScriptTarget.Latest */, /*skipTrivia*/ true); var disallowInAndDecoratorContext = 4096 /* NodeFlags.DisallowInContext */ | 16384 /* NodeFlags.DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name function countNode(node) { nodeCount++; return node; @@ -33089,8 +33132,9 @@ var ts; // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); var text = internIdentifier(scanner.getTokenValue()); + var hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape(); nextTokenWithoutCheck(); - return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos); + return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind, hasExtendedUnicodeEscape), pos); } if (token() === 80 /* SyntaxKind.PrivateIdentifier */) { parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); @@ -42229,12 +42273,23 @@ var ts; } function writeConfigurations() { // Filter applicable options to place in the file - var categorizedOptions = ts.createMultiMap(); + var categorizedOptions = new ts.Map(); + // Set allowed categories in order + categorizedOptions.set(ts.Diagnostics.Projects, []); + categorizedOptions.set(ts.Diagnostics.Language_and_Environment, []); + categorizedOptions.set(ts.Diagnostics.Modules, []); + categorizedOptions.set(ts.Diagnostics.JavaScript_Support, []); + categorizedOptions.set(ts.Diagnostics.Emit, []); + categorizedOptions.set(ts.Diagnostics.Interop_Constraints, []); + categorizedOptions.set(ts.Diagnostics.Type_Checking, []); + categorizedOptions.set(ts.Diagnostics.Completeness, []); for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { var option = optionDeclarations_1[_i]; - var category = option.category; if (isAllowedOptionForOutput(option)) { - categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + var listForCategory = categorizedOptions.get(option.category); + if (!listForCategory) + categorizedOptions.set(option.category, listForCategory = []); + listForCategory.push(option); } } // Serialize all options and their descriptions @@ -42245,7 +42300,7 @@ var ts; if (entries.length !== 0) { entries.push({ value: "" }); } - entries.push({ value: "/* ".concat(category, " */") }); + entries.push({ value: "/* ".concat(ts.getLocaleSpecificMessage(category), " */") }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -44287,6 +44342,9 @@ var ts; requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; + if (traceEnabled && ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) <= ts.ModuleResolutionKind.NodeNext) { + trace(host, ts.Diagnostics.Resolving_in_0_mode_with_conditions_1, features & NodeResolutionFeatures.EsmMode ? "ESM" : "CJS", conditions.map(function (c) { return "'".concat(c, "'"); }).join(", ")); + } var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { @@ -44876,7 +44934,7 @@ var ts; } if (mainExport) { var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false); - return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false, "."); } } else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) { @@ -44956,7 +45014,7 @@ var ts; var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!ts.endsWith(moduleName, ts.directorySeparator) && moduleName.indexOf("*") === -1 && ts.hasProperty(lookupTable, moduleName)) { var target = lookupTable[moduleName]; - return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName); } var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), comparePatternKeys); for (var _i = 0, expandingKeys_1 = expandingKeys; _i < expandingKeys_1.length; _i++) { @@ -44965,17 +45023,17 @@ var ts; var target = lookupTable[potentialTarget]; var starPos = potentialTarget.indexOf("*"); var subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.endsWith(potentialTarget, "*") && ts.startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length - 1); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.startsWith(moduleName, potentialTarget)) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false, potentialTarget); } } function matchesPatternWithTrailer(target, name) { @@ -44992,7 +45050,7 @@ var ts; */ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) { return loadModuleFromTargetImportOrExport; - function loadModuleFromTargetImportOrExport(target, subpath, pattern) { + function loadModuleFromTargetImportOrExport(target, subpath, pattern, key) { if (typeof target === "string") { if (!pattern && subpath.length > 0 && !ts.endsWith(target, "/")) { if (state.traceEnabled) { @@ -45003,6 +45061,8 @@ var ts; if (!ts.startsWith(target, "./")) { if (isImports && !ts.startsWith(target, "../") && !ts.startsWith(target, "/") && !ts.isRootedDiskPath(target)) { var combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath; + traceIfEnabled(state, ts.Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup); + traceIfEnabled(state, ts.Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/"); var result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, [extensions], redirectedReference); return toSearchResult(result.resolvedModule ? { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId, originalPath: result.resolvedModule.originalPath } : undefined); } @@ -45029,6 +45089,9 @@ var ts; } return toSearchResult(/*value*/ undefined); } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); + } var finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); var inputLink = tryLoadInputFileForPath(finalPath, subpath, ts.combinePaths(scope.packageDirectory, "package.json"), isImports); if (inputLink) @@ -45038,14 +45101,18 @@ var ts; else if (typeof target === "object" && target !== null) { // eslint-disable-line no-null/no-null if (!Array.isArray(target)) { for (var _i = 0, _a = ts.getOwnKeys(target); _i < _a.length; _i++) { - var key = _a[_i]; - if (key === "default" || state.conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(state.conditions, key)) { - var subTarget = target[key]; - var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern); + var condition = _a[_i]; + if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) { + traceIfEnabled(state, ts.Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition); + var subTarget = target[condition]; + var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key); if (result) { return result; } } + else { + traceIfEnabled(state, ts.Diagnostics.Saw_non_matching_condition_0, condition); + } } return undefined; } @@ -45058,7 +45125,7 @@ var ts; } for (var _b = 0, target_2 = target; _b < target_2.length; _b++) { var elem = target_2[_b]; - var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern); + var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern, key); if (result) { return result; } @@ -45474,6 +45541,15 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } + function traceIfEnabled(state, diagnostic) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (state.traceEnabled) { + trace.apply(void 0, __spreadArray([state.host, diagnostic], args, false)); + } + } })(ts || (ts = {})); /* @internal */ var ts; @@ -49065,8 +49141,6 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; - IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var RecursionFlags; (function (RecursionFlags) { @@ -49485,6 +49559,12 @@ var ts; getOptionalType: function () { return optionalType; }, getPromiseType: function () { return getGlobalPromiseType(/*reportErrors*/ false); }, getPromiseLikeType: function () { return getGlobalPromiseLikeType(/*reportErrors*/ false); }, + getAsyncIterableType: function () { + var type = getGlobalAsyncIterableType(/*reportErrors*/ false); + if (type === emptyGenericType) + return undefined; + return type; + }, isSymbolAccessible: isSymbolAccessible, isArrayType: isArrayType, isTupleType: isTupleType, @@ -50322,9 +50402,9 @@ var ts; return symbol; } if (symbol.flags & 2097152 /* SymbolFlags.Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { + var targetFlags = getAllSymbolFlags(symbol); + // `targetFlags` will be `SymbolFlags.All` if an error occurred in alias resolution; this avoids cascading errors + if (targetFlags & meaning) { return symbol; } } @@ -50957,8 +51037,8 @@ var ts; !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && + !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; var suggestedLib = void 0; @@ -51045,7 +51125,7 @@ var ts; } } if (result && errorLocation && meaning & 111551 /* SymbolFlags.Value */ && result.flags & 2097152 /* SymbolFlags.Alias */ && !(result.flags & 111551 /* SymbolFlags.Value */) && !ts.isValidTypeOnlyAliasUseSite(errorLocation)) { - var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); + var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551 /* SymbolFlags.Value */); if (typeOnlyDeclaration) { var message = typeOnlyDeclaration.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type @@ -51208,7 +51288,7 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { + if (meaning & 111551 /* SymbolFlags.Value */) { if (isPrimitiveTypeName(name)) { if (isExtendedByInterface(errorLocation)) { error(errorLocation, ts.Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, ts.unescapeLeadingUnderscores(name)); @@ -51219,7 +51299,8 @@ var ts; return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); - if (symbol && !(symbol.flags & 1024 /* SymbolFlags.NamespaceModule */)) { + var allFlags = symbol && getAllSymbolFlags(symbol); + if (symbol && allFlags !== undefined && !(allFlags & 111551 /* SymbolFlags.Value */)) { var rawName = ts.unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName); @@ -51267,16 +51348,16 @@ var ts; } return false; } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~788968 /* SymbolFlags.Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) { + if (meaning & (111551 /* SymbolFlags.Value */ & ~788968 /* SymbolFlags.Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (788968 /* SymbolFlags.Type */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* SymbolFlags.ValueModule */ | 1024 /* SymbolFlags.NamespaceModule */) & ~788968 /* SymbolFlags.Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1536 /* SymbolFlags.Module */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -51866,6 +51947,52 @@ var ts; } return undefined; } + /** + * Gets combined flags of a `symbol` and all alias targets it resolves to. `resolveAlias` + * is typically recursive over chains of aliases, but stops mid-chain if an alias is merged + * with another exported symbol, e.g. + * ```ts + * // a.ts + * export const a = 0; + * // b.ts + * export { a } from "./a"; + * export type a = number; + * // c.ts + * import { a } from "./b"; + * ``` + * Calling `resolveAlias` on the `a` in c.ts would stop at the merged symbol exported + * from b.ts, even though there is still more alias to resolve. Consequently, if we were + * trying to determine if the `a` in c.ts has a value meaning, looking at the flags on + * the local symbol and on the symbol returned by `resolveAlias` is not enough. + * @returns SymbolFlags.All if `symbol` is an alias that ultimately resolves to `unknown`; + * combined flags of all alias targets otherwise. + */ + function getAllSymbolFlags(symbol) { + var flags = symbol.flags; + var seenSymbols; + while (symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return 67108863 /* SymbolFlags.All */; + } + // Optimizations - try to avoid creating or adding to + // `seenSymbols` if possible + if (target === symbol || (seenSymbols === null || seenSymbols === void 0 ? void 0 : seenSymbols.has(target))) { + break; + } + if (target.flags & 2097152 /* SymbolFlags.Alias */) { + if (seenSymbols) { + seenSymbols.add(target); + } + else { + seenSymbols = new ts.Set([symbol, target]); + } + } + flags |= target.flags; + symbol = target; + } + return flags; + } /** * Marks a symbol as type-only if its declaration is syntactically type-only. * If it is not itself marked type-only, but resolves to a type-only alias @@ -51911,19 +52038,25 @@ var ts; return !!aliasDeclarationLinks.typeOnlyDeclaration; } /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */ - function getTypeOnlyAliasDeclaration(symbol) { + function getTypeOnlyAliasDeclaration(symbol, include) { if (!(symbol.flags & 2097152 /* SymbolFlags.Alias */)) { return undefined; } var links = getSymbolLinks(symbol); - return links.typeOnlyDeclaration || undefined; + if (include === undefined) { + return links.typeOnlyDeclaration || undefined; + } + if (links.typeOnlyDeclaration) { + return getAllSymbolFlags(resolveAlias(links.typeOnlyDeclaration.symbol)) & include ? links.typeOnlyDeclaration : undefined; + } + return undefined; } function markExportAsReferenced(node) { var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol)); + ((getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -51943,8 +52076,7 @@ var ts; // This way a chain of imports can be elided if ultimately the final input is only used in a type // position. if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveSymbol(symbol); - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* SymbolFlags.Value */) { // import foo = checkExpressionCached(node.moduleReference); } @@ -52766,7 +52898,7 @@ var ts; } function symbolIsValue(symbol, includeTypeOnlyMembers) { return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || - symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + symbol.flags & 2097152 /* SymbolFlags.Alias */ && getAllSymbolFlags(symbol) & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -53035,8 +53167,10 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { + var shouldResolveAlias = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)); + symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + var flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + if (flags & meaning) { qualify = true; return true; } @@ -55348,7 +55482,7 @@ var ts; // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it var indices = ts.indicesOf(statements); var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); }); - if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) { + if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return ts.canHaveExportModifier(statements[i]); })) { for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) { var index_1 = associatedIndices_1[_i]; statements[index_1] = addExportModifier(statements[index_1]); @@ -55382,15 +55516,6 @@ var ts; } return statements; } - function canHaveExportModifier(node) { - return ts.isEnumDeclaration(node) || - ts.isVariableStatement(node) || - ts.isFunctionDeclaration(node) || - ts.isClassDeclaration(node) || - (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) || - ts.isInterfaceDeclaration(node) || - isTypeDeclaration(node); - } function addExportModifier(node) { var flags = (ts.getEffectiveModifierFlags(node) | 1 /* ModifierFlags.Export */) & ~2 /* ModifierFlags.Ambient */; return ts.factory.updateModifiers(node, flags); @@ -55637,7 +55762,7 @@ var ts; (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* ModifierFlags.Export */ && enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && - canHaveExportModifier(node)) { + ts.canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* ModifierFlags.Export */; } @@ -55693,7 +55818,7 @@ var ts; return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { - return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* SymbolFlags.Value */); }); + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* SymbolFlags.Value */); }); } function serializeModule(symbol, symbolName, modifierFlags) { var members = getNamespaceMembersForSerialization(symbol); @@ -57913,7 +58038,7 @@ var ts; links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType - : targetSymbol.flags & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) + : getAllSymbolFlags(targetSymbol) & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; @@ -59796,7 +59921,20 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ && getMappedTypeModifiers(type) & 4 /* MappedTypeModifiers.IncludeOptional */); } function isGenericMappedType(type) { - return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + if (ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) { + var constraint = getConstraintTypeFromMappedType(type); + if (isGenericIndexType(constraint)) { + return true; + } + // A mapped type is generic if the 'as' clause references generic types other than the iteration type. + // To determine this, we substitute the constraint type (that we now know isn't generic) for the iteration + // type and check whether the resulting type is generic. + var nameType = getNameTypeFromMappedType(type); + if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) { + return true; + } + } + return false; } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -60266,7 +60404,7 @@ var ts; var indexTypes; var isUnion = containingType.flags & 1048576 /* TypeFlags.Union */; // Flags we want to propagate to the result if they exist in all source symbols - var optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */; + var optionalFlag; var syntheticFlag = 4 /* CheckFlags.SyntheticMethod */; var checkFlags = isUnion ? 0 : 8 /* CheckFlags.Readonly */; var mergedInstantiations = false; @@ -60277,11 +60415,14 @@ var ts; var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop) { - if (isUnion) { - optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); - } - else { - optionalFlag &= prop.flags; + if (prop.flags & 106500 /* SymbolFlags.ClassMember */) { + optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : (optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */); + if (isUnion) { + optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); + } + else { + optionalFlag &= prop.flags; + } } if (!singleProp) { singleProp = prop; @@ -60400,7 +60541,7 @@ var ts; propTypes.push(type); } ts.addRange(propTypes, indexTypes); - var result = createSymbol(4 /* SymbolFlags.Property */ | optionalFlag, name, syntheticFlag | checkFlags); + var result = createSymbol(4 /* SymbolFlags.Property */ | (optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : 0), name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && firstValueDeclaration) { result.valueDeclaration = firstValueDeclaration; @@ -63113,8 +63254,14 @@ var ts; return getStringLiteralType(text); } newTexts.push(text); - if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { - return stringType; + if (ts.every(newTexts, function (t) { return t === ""; })) { + if (ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { + return stringType; + } + // Normalize `${Mapping}` into Mapping + if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) { + return newTypes[0]; + } } var id = "".concat(getTypeListId(newTypes), "|").concat(ts.map(newTexts, function (t) { return t.length; }).join(","), "|").concat(newTexts.join("")); var type = templateLiteralTypes.get(id); @@ -63173,12 +63320,14 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - // Mapping> === Mapping - type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : - isGenericIndexType(type) || isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, isPatternLiteralPlaceholderType(type) && !(type.flags & 268435456 /* TypeFlags.StringMapping */) ? getTemplateLiteralType(["", ""], [type]) : type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : - type; + type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : + type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : + // Mapping> === Mapping + type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : + type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : + // This handles Mapping<`${number}`> and Mapping<`${bigint}`> + isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : + type; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -63343,7 +63492,18 @@ var ts; return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; } errorIfWritingToReadonlyIndex(indexInfo); - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; + // When accessing an enum object with its own type, + // e.g. E[E.A] for enum E { A }, undefined shouldn't + // be included in the result type + if ((accessFlags & 1 /* AccessFlags.IncludeUndefined */) && + !(objectType.symbol && + objectType.symbol.flags & (256 /* SymbolFlags.RegularEnum */ | 128 /* SymbolFlags.ConstEnum */) && + (indexType.symbol && + indexType.flags & 1024 /* TypeFlags.EnumLiteral */ && + getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + return getUnionType([indexInfo.type, undefinedType]); + } + return indexInfo.type; } if (indexType.flags & 131072 /* TypeFlags.Never */) { return neverType; @@ -63446,10 +63606,11 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || isPatternLiteralType(type); } function isPatternLiteralType(type) { - return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); + return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType) || + !!(type.flags & 268435456 /* TypeFlags.StringMapping */) && isPatternLiteralPlaceholderType(type.type); } function isGenericType(type) { return !!getGenericObjectFlags(type); @@ -63728,18 +63889,23 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_20 = function () { + // We loop here for an immediately nested conditional type in the false position, effectively treating + // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for + // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of + // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive + // cases we increment the tail recursion counter and stop after 1000 iterations. + while (true) { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; - return "break"; + break; } var isUnwrapped = isTypicalNondistributiveConditional(root); var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { - return { value: wildcardType }; + return wildcardType; } var combinedMapper = void 0; if (root.inferTypeParameters) { @@ -63772,11 +63938,7 @@ var ts; } } } - // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type - // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to - // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint - // so in those cases we refain from performing inference and retain the uninfered type parameter - if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -63808,14 +63970,14 @@ var ts; var newRoot = falseType_1.root; if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) { root = newRoot; - return "continue"; + continue; } if (canTailRecurse(falseType_1, mapper)) { - return "continue"; + continue; } } result = instantiateType(falseType_1, mapper); - return "break"; + break; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -63826,10 +63988,10 @@ var ts; var trueType_1 = getTypeFromTypeNode(root.node.trueType); var trueMapper = combinedMapper || mapper; if (canTailRecurse(trueType_1, trueMapper)) { - return "continue"; + continue; } result = instantiateType(trueType_1, trueMapper); - return "break"; + break; } } // Return a deferred type for a check that is neither definitely true nor definitely false @@ -63841,19 +64003,7 @@ var ts; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 - return "break"; - }; - // We loop here for an immediately nested conditional type in the false position, effectively treating - // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for - // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of - // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive - // cases we increment the tail recursion counter and stop after 1000 iterations. - while (true) { - var state_6 = _loop_20(); - if (typeof state_6 === "object") - return state_6.value; - if (state_6 === "break") - break; + break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; // We tail-recurse for generic conditional types that (a) have not already been evaluated and cached, and @@ -66307,7 +66457,7 @@ var ts; return 0 /* Ternary.False */; } } - var isPerformingCommonPropertyChecks = (relation !== comparableRelation || !(source.flags & 1048576 /* TypeFlags.Union */) && isLiteralType(source)) && + var isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source)) && !(intersectionState & 2 /* IntersectionState.Target */) && source.flags & (131068 /* TypeFlags.Primitive */ | 524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && source !== globalObjectType && target.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && isWeakType(target) && @@ -66335,27 +66485,6 @@ var ts; var result_7 = skipCaching ? unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) : recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags); - // For certain combinations involving intersections and optional, excess, or mismatched properties we need - // an extra property check where the intersection is viewed as a single object. The following are motivating - // examples that all should be errors, but aren't without this extra property check: - // - // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property - // - // declare let wrong: { a: { y: string } }; - // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type - // - // function foo(x: { a?: string }, y: T & { a: boolean }) { - // x = y; // Mismatched property in source intersection - // } - // - // We suppress recursive intersection property checks because they can generate lots of work when relating - // recursive intersections that are structurally similar but not exactly identical. See #37854. - if (result_7 && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { - inPropertyCheck = true; - result_7 &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* IntersectionState.PropertyCheck */, recursionFlags); - inPropertyCheck = false; - } if (result_7) { return result_7; } @@ -66467,7 +66596,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_21 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -66530,9 +66659,9 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_7 = _loop_21(prop); - if (typeof state_7 === "object") - return state_7.value; + var state_6 = _loop_20(prop); + if (typeof state_6 === "object") + return state_6.value; } return false; } @@ -66753,8 +66882,7 @@ var ts; if (overflow) { return 0 /* Ternary.False */; } - var keyIntersectionState = intersectionState | (inPropertyCheck ? 8 /* IntersectionState.InPropertyCheck */ : 0); - var id = getRelationKey(source, target, keyIntersectionState, relation, /*ingnoreConstraints*/ false); + var id = getRelationKey(source, target, intersectionState, relation, /*ingnoreConstraints*/ false); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* RelationComparisonResult.Failed */ && !(entry & 4 /* RelationComparisonResult.Reported */)) { @@ -66784,7 +66912,7 @@ var ts; // A key that starts with "*" is an indication that we have type references that reference constrained // type parameters. For such keys we also check against the key we would have gotten if all type parameters // were unconstrained. - var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, keyIntersectionState, relation, /*ignoreConstraints*/ true) : undefined; + var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, intersectionState, relation, /*ignoreConstraints*/ true) : undefined; for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { @@ -66871,7 +66999,7 @@ var ts; function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { var saveErrorInfo = captureErrorCalculationState(); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo); - if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + if (relation !== identityRelation) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -66885,10 +67013,33 @@ var ts; // needs to have its constraint hoisted into an intersection with said type parameter, this way // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` - var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); - if (constraint && !(constraint.flags & 131072 /* TypeFlags.Never */) && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself - // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this - result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); + if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself + // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this + result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + } + } + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && !isGenericObjectType(target) && source.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) || + isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { + inPropertyCheck = true; + result &= propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); + inPropertyCheck = false; } } if (result) { @@ -66897,9 +67048,6 @@ var ts; return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo) { - if (intersectionState & 4 /* IntersectionState.PropertyCheck */) { - return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); - } var result; var originalErrorInfo; var varianceCheckFailed = false; @@ -67000,7 +67148,7 @@ var ts; // with another type parameter unless one extends the other. (Remember: comparability is mostly bidirectional!) var constraint = getConstraintOfTypeParameter(source); if (constraint && hasNonCircularBaseConstraint(source)) { - while (constraint && constraint.flags & 262144 /* TypeFlags.TypeParameter */) { + while (constraint && someType(constraint, function (c) { return !!(c.flags & 262144 /* TypeFlags.TypeParameter */); })) { if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { return result; } @@ -67523,11 +67671,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_22 = function (combination) { + var _loop_21 = function (combination) { var hasMatch = false; outer: for (var _c = 0, _d = target.types; _c < _d.length; _c++) { var type = _d[_c]; - var _loop_23 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -67543,8 +67691,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_9 = _loop_23(i); - switch (state_9) { + var state_8 = _loop_22(i); + switch (state_8) { case "continue-outer": continue outer; } } @@ -67557,9 +67705,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_8 = _loop_22(combination); - if (typeof state_8 === "object") - return state_8.value; + var state_7 = _loop_21(combination); + if (typeof state_7 === "object") + return state_7.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* Ternary.True */; @@ -67656,7 +67804,7 @@ var ts; return 0 /* Ternary.False */; } // When checking for comparability, be more lenient with optional properties. - if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && targetProp.flags & 106500 /* SymbolFlags.ClassMember */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -68264,7 +68412,7 @@ var ts; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); links.variances = ts.emptyArray; var variances = []; - var _loop_24 = function (tp) { + var _loop_23 = function (tp) { var modifiers = getVarianceModifiers(tp); var variance = modifiers & 65536 /* ModifierFlags.Out */ ? modifiers & 32768 /* ModifierFlags.In */ ? 0 /* VarianceFlags.Invariant */ : 1 /* VarianceFlags.Covariant */ : @@ -68302,7 +68450,7 @@ var ts; }; for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var tp = typeParameters_2[_i]; - _loop_24(tp); + _loop_23(tp); } links.variances = variances; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); @@ -68756,8 +68904,7 @@ var ts; return !!(type.flags & 109440 /* TypeFlags.Unit */); } function isUnitLikeType(type) { - return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.some(type.types, isUnitType) : - !!(type.flags & 109440 /* TypeFlags.Unit */); + return isUnitType(getBaseConstraintOrType(type)); } function extractUnitType(type) { return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.find(type.types, isUnitType) || type : type; @@ -69636,7 +69783,7 @@ var ts; && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); } function isMemberOfStringMapping(source, target) { - if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + if (target.flags & (4 /* TypeFlags.String */ | 1 /* TypeFlags.Any */)) { return true; } if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { @@ -70260,7 +70407,7 @@ var ts; // upon instantiation, would collapse all the placeholders to just 'string', and an assignment check might // succeed. That would be a pointless and confusing outcome. if (matches || ts.every(target.texts, function (s) { return s.length === 0; })) { - var _loop_25 = function (i) { + var _loop_24 = function (i) { var source_1 = matches ? matches[i] : neverType; var target_3 = types[i]; // If we are inferring from a string literal type to a type variable whose constraint includes one of the @@ -70310,7 +70457,7 @@ var ts; inferFromTypes(source_1, target_3); }; for (var i = 0; i < types.length; i++) { - _loop_25(i); + _loop_24(i); } } } @@ -70762,7 +70909,7 @@ var ts; } if (ts.isEntityNameExpression(node.argumentExpression)) { var symbol = resolveEntityName(node.argumentExpression, 111551 /* SymbolFlags.Value */, /*ignoreErrors*/ true); - if (!symbol || !isConstVariable(symbol)) + if (!symbol || !(isConstVariable(symbol) || (symbol.flags & 8 /* SymbolFlags.EnumMember */))) return undefined; var declaration = symbol.valueDeclaration; if (declaration === undefined) @@ -70776,7 +70923,12 @@ var ts; } if (ts.hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node.argumentExpression)) { var initializer = ts.getEffectiveInitializer(declaration); - return initializer && tryGetNameFromType(getTypeOfExpression(initializer)); + if (initializer) { + return tryGetNameFromType(getTypeOfExpression(initializer)); + } + if (ts.isEnumMember(declaration)) { + return ts.getTextOfPropertyName(declaration.name); + } } } return undefined; @@ -70834,7 +70986,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_26 = function (type) { + var _loop_25 = function (type) { if (type.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */ | 58982400 /* TypeFlags.InstantiableNonPrimitive */)) { var discriminant = getTypeOfPropertyOfType(type, name); if (discriminant) { @@ -70860,9 +71012,9 @@ var ts; }; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var type = types_15[_i]; - var state_10 = _loop_26(type); - if (typeof state_10 === "object") - return state_10.value; + var state_9 = _loop_25(type); + if (typeof state_9 === "object") + return state_9.value; } return count >= 10 && count * 2 >= types.length ? map : undefined; } @@ -71459,6 +71611,7 @@ var ts; ts.isInJSFile(node) && ts.hasInitializer(node) && node.initializer && ts.isFunctionExpressionOrArrowFunction(node.initializer) && ts.getEffectiveReturnTypeNode(node.initializer)); } function getExplicitTypeOfSymbol(symbol, diagnostic) { + symbol = resolveSymbol(symbol); if (symbol.flags & (16 /* SymbolFlags.Function */ | 8192 /* SymbolFlags.Method */ | 32 /* SymbolFlags.Class */ | 512 /* SymbolFlags.ValueModule */)) { return getTypeOfSymbol(symbol); } @@ -71497,7 +71650,7 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); - return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol, diagnostic); + return getExplicitTypeOfSymbol(symbol, diagnostic); case 108 /* SyntaxKind.ThisKeyword */: return getExplicitThisType(node); case 106 /* SyntaxKind.SuperKeyword */: @@ -71984,7 +72137,7 @@ var ts; type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (expr.kind === 218 /* SyntaxKind.TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { - type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { if (strictNullChecks) { @@ -72265,7 +72418,7 @@ var ts; !!(prop.flags & 16777216 /* SymbolFlags.Optional */) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue; } - function narrowByInKeyword(type, nameType, assumeTrue) { + function narrowTypeByInKeyword(type, nameType, assumeTrue) { var name = getPropertyNameFromType(nameType); var isKnownProperty = someType(type, function (t) { return isTypePresencePossible(t, name, /*assumeTrue*/ true); }); if (isKnownProperty) { @@ -72346,7 +72499,7 @@ var ts; return getTypeWithFacts(type, assumeTrue ? 524288 /* TypeFacts.NEUndefined */ : 65536 /* TypeFacts.EQUndefined */); } if (isMatchingReference(reference, target)) { - return narrowByInKeyword(type, leftType, assumeTrue); + return narrowTypeByInKeyword(type, leftType, assumeTrue); } } break; @@ -72535,7 +72688,7 @@ var ts; neverType; }); } - function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + function narrowTypeBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!witnesses) { return type; @@ -72923,15 +73076,15 @@ var ts; }); } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { var target = resolveAlias(symbol); - if (target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */)) { // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled // (because the const enum value will not be inlined), or if (2) the alias is an export // of a const enum declaration that will be preserved. if (compilerOptions.isolatedModules || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || - !isConstEnumOrConstEnumOnlyModule(target)) { + !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -73159,7 +73312,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 16384 /* TypeFlags.Void */)) !== 0 || isInTypeQuery(node) || node.parent.kind === 278 /* SyntaxKind.ExportSpecifier */) || node.parent.kind === 232 /* SyntaxKind.NonNullExpression */ || @@ -73188,6 +73341,12 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function isSameScopedBindingElement(node, declaration) { + if (ts.isBindingElement(declaration)) { + var bindingElement = ts.findAncestor(node, ts.isBindingElement); + return bindingElement && ts.getRootDeclaration(bindingElement) === ts.getRootDeclaration(declaration); + } + } function shouldMarkIdentifierAliasReferenced(node) { var _a; var parent = node.parent; @@ -73529,12 +73688,17 @@ var ts; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; + var inAsyncFunction = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { while (container && container.kind === 216 /* SyntaxKind.ArrowFunction */) { + if (ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ScriptTarget.ES2015 */; } + if (container && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; @@ -73640,12 +73804,12 @@ var ts; // as a call expression cannot be used as the target of a destructuring assignment while a property access can. // // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. - if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) { + if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && inAsyncFunction) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */; + getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */; } else { - getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.AsyncMethodWithSuper */; + getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */; } } if (needToCaptureLexicalThis) { @@ -74341,9 +74505,10 @@ var ts; function instantiateContextualType(contextualType, node, contextFlags) { if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* TypeFlags.Instantiable */)) { var inferenceContext = getInferenceContext(node); - // If no inferences have been made, nothing is gained from instantiating as type parameters - // would just be replaced with their defaults similar to the apparent type. - if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + // If no inferences have been made, and none of the type parameters for which we are inferring + // specify default types, nothing is gained from instantiating as type parameters would just be + // replaced with their constraints similar to the apparent type. + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) { // For contextual signatures we incorporate all inferences made so far, e.g. from return // types as well as arguments to the left in a function call. return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); @@ -77317,7 +77482,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_27 = function (i) { + var _loop_26 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. var spreadType = arg.kind === 227 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -77334,7 +77499,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_27(i); + _loop_26(i); } return effectiveArgs_1; } @@ -77663,7 +77828,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_28 = function (c) { + var _loop_27 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* CheckMode.Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -77681,7 +77846,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_28(c); + _loop_27(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -77839,7 +78004,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_29 = function (i) { + var _loop_28 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -77847,7 +78012,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_29(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -78817,7 +78982,7 @@ var ts; if (symbol && symbol.flags & 2097152 /* SymbolFlags.Alias */) { symbol = resolveAlias(symbol); } - return !!(symbol && (symbol.flags & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); + return !!(symbol && (getAllSymbolFlags(symbol) & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); } return false; } @@ -79479,7 +79644,17 @@ var ts; } function isExhaustiveSwitchStatement(node) { var links = getNodeLinks(node); - return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); + if (links.isExhaustive === undefined) { + links.isExhaustive = 0; // Indicate resolution is in process + var exhaustive = computeExhaustiveSwitchStatement(node); + if (links.isExhaustive === 0) { + links.isExhaustive = exhaustive; + } + } + else if (links.isExhaustive === 0) { + links.isExhaustive = false; // Resolve circularity to false + } + return links.isExhaustive; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 218 /* SyntaxKind.TypeOfExpression */) { @@ -79487,7 +79662,7 @@ var ts; if (!witnesses) { return false; } - var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(node.expression.expression)); + var operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression)); // Get the not-equal flags for all handled cases. var notEqualFacts_2 = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); if (operandConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */) { @@ -79497,7 +79672,7 @@ var ts; // A missing not-equal flag indicates that the type wasn't handled by some case. return !someType(operandConstraint, function (t) { return (getTypeFacts(t) & notEqualFacts_2) === notEqualFacts_2; }); } - var type = getTypeOfExpression(node.expression); + var type = checkExpressionCached(node.expression); if (!isLiteralType(type)) { return false; } @@ -81191,6 +81366,9 @@ var ts; function hasInferenceCandidates(info) { return !!(info.candidates || info.contraCandidates); } + function hasInferenceCandidatesOrDefault(info) { + return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter)); + } function hasOverlappingInferences(a, b) { for (var i = 0; i < a.length; i++) { if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) { @@ -81892,7 +82070,7 @@ var ts; var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var indexSignatureMap_1 = new ts.Map(); - var _loop_30 = function (declaration) { + var _loop_29 = function (declaration) { if (declaration.parameters.length === 1 && declaration.parameters[0].type) { forEachType(getTypeFromTypeNode(declaration.parameters[0].type), function (type) { var entry = indexSignatureMap_1.get(getTypeId(type)); @@ -81907,7 +82085,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_30(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -82184,7 +82362,7 @@ var ts; } var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { - if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { + if (ts.some(symbol.declarations, function (d) { return ts.isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* TypeFlags.Enum */ && symbol.flags & 8 /* SymbolFlags.EnumMember */) { @@ -82787,7 +82965,7 @@ var ts; return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; } // primitives with a `{ then() }` won't be unwrapped/adopted. - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217 @@ -82854,7 +83032,7 @@ var ts; * Determines whether a type is an object with a callable `then` member. */ function isThenableType(type) { - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { // primitive types cannot be considered "thenable" since they are not objects. return false; } @@ -82888,7 +83066,7 @@ var ts; // We only need `Awaited` if `T` is a type variable that has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`, // or is promise-like. if (baseConstraint ? - baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint) : + baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { return true; } @@ -83562,7 +83740,7 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + var message = ts.isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(declaration, 0 /* UnusedKind.Local */, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { @@ -84992,7 +85170,16 @@ var ts; var message = allowAsyncIterables ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; - return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + var suggestAwait = + // for (const x of Promise<...>) or [...Promise<...>] + !!getAwaitedTypeOfPromise(type) + // for (const x of AsyncIterable<...>) + || (!allowAsyncIterables && + ts.isForOfStatement(errorNode.parent) && + errorNode.parent.expression === errorNode && + getGlobalAsyncIterableType(/** reportErrors */ false) !== emptyGenericType && + isTypeAssignableTo(type, getGlobalAsyncIterableType(/** reportErrors */ false))); + return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. @@ -85507,7 +85694,7 @@ var ts; var propDeclaration = declaration && declaration.kind === 223 /* SyntaxKind.BinaryExpression */ || name && name.kind === 164 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_31 = function (info) { + var _loop_30 = function (info) { var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; // We check only when (a) the property is declared in the containing type, or (b) the applicable index signature is declared // in the containing type, or (c) the containing type is an interface and no base interface contains both the property and @@ -85524,7 +85711,7 @@ var ts; }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_31(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -85532,7 +85719,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 261 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_32 = function (info) { + var _loop_31 = function (info) { if (info === checkInfo) return "continue"; var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; @@ -85547,7 +85734,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_32(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -85602,7 +85789,7 @@ var ts; } else { ts.forEach(jsdocParameters, function (_a, index) { - var name = _a.name; + var name = _a.name, isNameFirst = _a.isNameFirst; if (excludedParameters.has(index) || ts.isIdentifier(name) && parameters.has(name.escapedText)) { return; } @@ -85612,7 +85799,9 @@ var ts; } } else { - errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + if (!isNameFirst) { + errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + } } }); } @@ -85867,7 +86056,7 @@ var ts; 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 _loop_33 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -85884,7 +86073,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_33(member); + _loop_32(member); } } /** @@ -85972,7 +86161,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_34 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -85991,7 +86180,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_34(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -86062,7 +86251,7 @@ var ts; var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - var _loop_35 = function (baseProperty) { + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { return "continue"; @@ -86172,8 +86361,8 @@ var ts; }; basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { var baseProperty = baseProperties_1[_i]; - var state_11 = _loop_35(baseProperty); - switch (state_11) { + var state_10 = _loop_34(baseProperty); + switch (state_10) { case "continue-basePropertyCheck": continue basePropertyCheck; } } @@ -86692,12 +86881,11 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { - var _a; switch (node.kind) { case 240 /* SyntaxKind.VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { - var decl = _b[_i]; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; @@ -86713,8 +86901,8 @@ var ts; case 257 /* SyntaxKind.VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { - var el = _d[_c]; + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -86730,18 +86918,6 @@ var ts; if (isGlobalAugmentation) { return; } - var symbol = getSymbolOfNode(node); - if (symbol) { - // module augmentations cannot introduce new names on the top level scope of the module - // this is done it two steps - // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error - // 2. main check - report error if value declaration of the parent symbol is module augmentation) - var reportError = !(symbol.flags & 33554432 /* SymbolFlags.Transient */); - if (!reportError) { - // symbol should not originate in augmentation - reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } break; } } @@ -86843,10 +87019,11 @@ var ts; } return; } + var targetFlags = getAllSymbolFlags(target); var excludedMeanings = (symbol.flags & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */) ? 111551 /* SymbolFlags.Value */ : 0) | (symbol.flags & 788968 /* SymbolFlags.Type */ ? 788968 /* SymbolFlags.Type */ : 0) | (symbol.flags & 1920 /* SymbolFlags.Namespace */ ? 1920 /* SymbolFlags.Namespace */ : 0); - if (target.flags & excludedMeanings) { + if (targetFlags & excludedMeanings) { var message = node.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; @@ -86856,7 +87033,7 @@ var ts; && !ts.isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 16777216 /* NodeFlags.Ambient */)) { var typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol); - var isType = !(target.flags & 111551 /* SymbolFlags.Value */); + var isType = !(targetFlags & 111551 /* SymbolFlags.Value */); if (isType || typeOnlyAlias) { switch (node.kind) { case 270 /* SyntaxKind.ImportClause */: @@ -87016,14 +87193,15 @@ var ts; if (node.moduleReference.kind !== 280 /* SyntaxKind.ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 111551 /* SymbolFlags.Value */) { + var targetFlags = getAllSymbolFlags(target); + if (targetFlags & 111551 /* SymbolFlags.Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* SymbolFlags.Value */ | 1920 /* SymbolFlags.Namespace */).flags & 1920 /* SymbolFlags.Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 788968 /* SymbolFlags.Type */) { + if (targetFlags & 788968 /* SymbolFlags.Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -87162,7 +87340,7 @@ var ts; markExportAsReferenced(node); } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); - if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (!target || getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); } } @@ -87209,7 +87387,7 @@ var ts; markAliasReferenced(sym, id); // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`) var target = sym.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(sym) : sym; - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { // However if it is a value, we need to check it's being used correctly checkExpressionCached(node.expression); } @@ -87881,29 +88059,9 @@ var ts; } function isTypeDeclarationName(name) { return name.kind === 79 /* SyntaxKind.Identifier */ && - isTypeDeclaration(name.parent) && + ts.isTypeDeclaration(name.parent) && ts.getNameOfDeclaration(name.parent) === name; } - function isTypeDeclaration(node) { - switch (node.kind) { - case 165 /* SyntaxKind.TypeParameter */: - case 260 /* SyntaxKind.ClassDeclaration */: - case 261 /* SyntaxKind.InterfaceDeclaration */: - case 262 /* SyntaxKind.TypeAliasDeclaration */: - case 263 /* SyntaxKind.EnumDeclaration */: - case 348 /* SyntaxKind.JSDocTypedefTag */: - case 341 /* SyntaxKind.JSDocCallbackTag */: - case 342 /* SyntaxKind.JSDocEnumTag */: - return true; - case 270 /* SyntaxKind.ImportClause */: - return node.isTypeOnly; - case 273 /* SyntaxKind.ImportSpecifier */: - case 278 /* SyntaxKind.ExportSpecifier */: - return node.parent.parent.isTypeOnly; - default: - return false; - } - } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { while (node.parent.kind === 163 /* SyntaxKind.QualifiedName */) { @@ -88336,7 +88494,7 @@ var ts; var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } - if (isTypeDeclaration(node)) { + if (ts.isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration var symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); @@ -88531,7 +88689,7 @@ var ts; return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 111551 /* SymbolFlags.Value */); + return s && !!(getAllSymbolFlags(s) & 111551 /* SymbolFlags.Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -88584,7 +88742,7 @@ var ts; var symbol = getReferencedValueOrAliasSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -88672,7 +88830,7 @@ var ts; case 273 /* SyntaxKind.ImportSpecifier */: case 278 /* SyntaxKind.ExportSpecifier */: var symbol = getSymbolOfNode(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); + return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */); case 275 /* SyntaxKind.ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || @@ -88694,6 +88852,7 @@ var ts; return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); } function isAliasResolvedToValue(symbol) { + var _a; if (!symbol) { return false; } @@ -88703,7 +88862,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 111551 /* SymbolFlags.Value */) && + return !!(((_a = getAllSymbolFlags(target)) !== null && _a !== void 0 ? _a : -1) & 111551 /* SymbolFlags.Value */) && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -88718,7 +88877,7 @@ var ts; } var target = getSymbolLinks(symbol).aliasTarget; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* ModifierFlags.Export */ && - target.flags & 111551 /* SymbolFlags.Value */ && + getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */ && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; @@ -98372,8 +98531,11 @@ var ts; } return ts.visitEachChild(node, visitor, context); case 174 /* SyntaxKind.GetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitGetAccessorDeclaration, node); case 175 /* SyntaxKind.SetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitSetAccessorDeclaration, node); case 173 /* SyntaxKind.Constructor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitConstructorDeclaration, node); case 260 /* SyntaxKind.ClassDeclaration */: case 228 /* SyntaxKind.ClassExpression */: return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitDefault, node); @@ -98474,6 +98636,9 @@ var ts; return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression( /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); + } /** * Visits a MethodDeclaration node. * @@ -98488,7 +98653,14 @@ var ts; /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) - : ts.visitFunctionBody(node.body, visitor, context)); + : transformMethodBody(node)); + } + function visitGetAccessorDeclaration(node) { + return factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformMethodBody(node)); + } + function visitSetAccessorDeclaration(node) { + return factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); } /** * Visits a FunctionDeclaration node. @@ -98602,6 +98774,42 @@ var ts; } return false; } + function transformMethodBody(node) { + ts.Debug.assertIsDefined(node.body); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = new ts.Set(); + hasSuperElementAccess = false; + var updated = ts.visitFunctionBody(node.body, visitor, context); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var originalMethod = ts.getOriginalNode(node, ts.isFunctionLikeDeclaration); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && + resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) && + (ts.getFunctionFlags(originalMethod) & 3 /* FunctionFlags.AsyncGenerator */) !== 3 /* FunctionFlags.AsyncGenerator */; + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + if (capturedSuperProperties.size) { + var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + var statements = updated.statements.slice(); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + updated = factory.updateBlock(updated, statements); + } + if (hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { + ts.addEmitHelper(updated, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { + ts.addEmitHelper(updated, ts.asyncSuperHelper); + } + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return updated; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -98634,7 +98842,7 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { @@ -98647,10 +98855,10 @@ var ts; ts.setTextRange(block, node.body); if (emitSuperHelpers && hasSuperElementAccess) { // Emit helpers for super element access expressions (`super[x]`). - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -98722,7 +98930,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ES2017SubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -98799,7 +99007,7 @@ var ts; || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -98814,7 +99022,7 @@ var ts; function createSuperAccessVariableStatement(factory, resolver, node, names) { // Create a variable declaration with a getter/setter (if binding) definition for each name: // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); - var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) !== 0; + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) !== 0; var accessors = []; names.forEach(function (_, key) { var name = ts.unescapeLeadingUnderscores(key); @@ -99307,11 +99515,22 @@ var ts; } return node; } - function convertForOfStatementHead(node, boundValue) { - var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue); + function convertForOfStatementHead(node, boundValue, nonUserCode) { + var value = factory.createTempVariable(hoistVariableDeclaration); + var iteratorValueExpression = factory.createAssignment(value, boundValue); + var iteratorValueStatement = factory.createExpressionStatement(iteratorValueExpression); + ts.setSourceMapRange(iteratorValueStatement, node.expression); + var exitNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createFalse()); + var exitNonUserCodeStatement = factory.createExpressionStatement(exitNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var enterNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createTrue()); + var enterNonUserCodeStatement = factory.createExpressionStatement(enterNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var statements = []; + var binding = ts.createForOfBindingStatement(factory, node.initializer, value); + statements.push(ts.visitNode(binding, visitor, ts.isStatement)); var bodyLocation; var statementsLocation; - var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); @@ -99321,8 +99540,16 @@ var ts; else { statements.push(statement); } - return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), + var body = ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* EmitFlags.NoSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */); + return factory.createBlock([ + iteratorValueStatement, + exitNonUserCodeStatement, + factory.createTryStatement(body, + /*catchClause*/ undefined, factory.createBlock([ + enterNonUserCodeStatement + ])) + ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ @@ -99333,6 +99560,8 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined); + var nonUserCode = factory.createTempVariable(/*recordTempVariable*/ undefined); + var done = factory.createTempVariable(hoistVariableDeclaration); var errorRecord = factory.createUniqueName("e"); var catchVariable = factory.getGeneratedNameForNode(errorRecord); var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined); @@ -99349,12 +99578,17 @@ var ts; callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement( /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([ + factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()), ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression), factory.createVariableDeclaration(result) ]), node.expression), 2097152 /* EmitFlags.NoHoisting */), - /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), + /*condition*/ factory.inlineExpressions([ + factory.createAssignment(result, createDownlevelAwait(callNext)), + factory.createAssignment(done, getDone), + factory.createLogicalNot(done) + ]), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, getValue)), + /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode)), /*location*/ node), 256 /* EmitFlags.NoTokenTrailingSourceMaps */); ts.setOriginalNode(forStatement, node); return factory.createTryStatement(factory.createBlock([ @@ -99366,7 +99600,7 @@ var ts; ]), 1 /* EmitFlags.SingleLine */)), factory.createBlock([ factory.createTryStatement( /*tryBlock*/ factory.createBlock([ - ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(getDone)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) + ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(factory.createLogicalNot(nonUserCode), factory.createLogicalNot(done)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([ @@ -99522,7 +99756,7 @@ var ts; /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HierarchyFacts.HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); @@ -99533,10 +99767,10 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = factory.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -99665,7 +99899,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ESNextSubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -99742,7 +99976,7 @@ var ts; || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -101211,11 +101445,13 @@ var ts; return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); } function visitIdentifier(node) { - if (!convertedLoopState) { - return node; + if (convertedLoopState) { + if (resolver.isArgumentsLocalBinding(node)) { + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + } } - if (resolver.isArgumentsLocalBinding(node)) { - return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + if (node.hasExtendedUnicodeEscape) { + return ts.setOriginalNode(ts.setTextRange(factory.createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText)), node), node); } return node; } @@ -105362,7 +105598,6 @@ var ts; return node; } function transformAndEmitForInStatement(node) { - // TODO(rbuckton): Source map locations if (containsYield(node)) { // [source] // for (var p in o) { @@ -105370,34 +105605,41 @@ var ts; // } // // [intermediate] - // .local _a, _b, _i - // _a = []; - // for (_b in o) _a.push(_b); + // .local _b, _a, _c, _i + // _b = []; + // _a = o; + // for (_c in _a) _b.push(_c); // _i = 0; // .loop incrementLabel, endLoopLabel // .mark conditionLabel - // .brfalse endLoopLabel, (_i < _a.length) - // p = _a[_i]; + // .brfalse endLoopLabel, (_i < _b.length) + // _c = _b[_i]; + // .brfalse incrementLabel, (_c in _a) + // p = _c; // /*body*/ // .mark incrementLabel - // _b++; + // _c++; // .br conditionLabel // .endloop // .mark endLoopLabel - var keysArray = declareLocal(); // _a - var key = declareLocal(); // _b + var obj = declareLocal(); // _a + var keysArray = declareLocal(); // _b + var key = declareLocal(); // _c var keysIndex = factory.createLoopVariable(); // _i var initializer = node.initializer; hoistVariableDeclaration(keysIndex); + emitAssignment(obj, ts.visitNode(node.expression, visitor, ts.isExpression)); emitAssignment(keysArray, factory.createArrayLiteralExpression()); - emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), + emitStatement(factory.createForInStatement(key, obj, factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), /*typeArguments*/ undefined, [key])))); emitAssignment(keysIndex, factory.createNumericLiteral(0)); var conditionLabel = defineLabel(); var incrementLabel = defineLabel(); - var endLabel = beginLoopBlock(incrementLabel); + var endLoopLabel = beginLoopBlock(incrementLabel); markLabel(conditionLabel); - emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitBreakWhenFalse(endLoopLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitAssignment(key, factory.createElementAccessExpression(keysArray, keysIndex)); + emitBreakWhenFalse(incrementLabel, factory.createBinaryExpression(key, 101 /* SyntaxKind.InKeyword */, obj)); var variable = void 0; if (ts.isVariableDeclarationList(initializer)) { for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { @@ -105410,7 +105652,7 @@ var ts; variable = ts.visitNode(initializer, visitor, ts.isExpression); ts.Debug.assert(ts.isLeftHandSideExpression(variable)); } - emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex)); + emitAssignment(variable, key); transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex))); @@ -107251,7 +107493,7 @@ var ts; return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return createImportCallExpressionCommonJS(argument, containsLexicalThis); + return createImportCallExpressionCommonJS(argument); } } function createImportCallExpressionUMD(arg, containsLexicalThis) { @@ -107274,7 +107516,7 @@ var ts; return factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(arg), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); } @@ -107283,7 +107525,7 @@ var ts; return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, /* isInlineable */ true), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); } @@ -107333,14 +107575,20 @@ var ts; } return promise; } - function createImportCallExpressionCommonJS(arg, containsLexicalThis) { - // import("./blah") + function createImportCallExpressionCommonJS(arg, isInlineable) { + // import(x) // emit as - // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // var _a; + // (_a = x, Promise.resolve().then(() => require(_a)) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); - var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + // If the arg is not inlineable, we have to evaluate it in the current scope with a temp var + var temp = arg && !ts.isSimpleInlineableExpression(arg) && !isInlineable ? factory.createTempVariable(hoistVariableDeclaration) : undefined; + var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), + /*typeArguments*/ undefined, + /*argumentsArray*/ []); + var requireCall = factory.createCallExpression(factory.createIdentifier("require"), + /*typeArguments*/ undefined, temp ? [temp] : arg ? [arg] : []); if (ts.getESModuleInterop(compilerOptions)) { requireCall = emitHelpers().createImportStarHelper(requireCall); } @@ -107361,14 +107609,9 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)])); - // if there is a lexical 'this' in the import call arguments, ensure we indicate - // that this new function expression indicates it captures 'this' so that the - // es2015 transformer will properly substitute 'this' with '_this'. - if (containsLexicalThis) { - ts.setEmitFlags(func, 8 /* EmitFlags.CapturesThis */); - } } - return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + var downleveledImport = factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + return temp === undefined ? downleveledImport : factory.createCommaListExpression([factory.createAssignment(temp, arg), downleveledImport]); } function getHelperExpressionForExport(node, innerExpr) { if (!ts.getESModuleInterop(compilerOptions) || ts.getEmitFlags(node) & 67108864 /* EmitFlags.NeverApplyImportHelper */) { @@ -122541,10 +122784,16 @@ var ts; var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + // We can only reuse emit signatures (i.e. .d.ts signatures) if the .d.ts file is unchanged, + // which will eg be depedent on change in options like declarationDir and outDir options are unchanged. + // We need to look in oldState.compilerOptions, rather than oldCompilerOptions (i.e.we need to disregard useOldState) because + // oldCompilerOptions can be undefined if there was change in say module from None to some other option + // which would make useOldState as false since we can now use reference maps that are needed to track what to emit, what to check etc + // but that option change does not affect d.ts file name so emitSignatures should still be reused. var canCopyEmitSignatures = compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && !outFilePath && - !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); if (useOldState) { // Copy old state's changed files set (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); @@ -123759,7 +124008,7 @@ var ts; var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* CharacterCodes.slash */; if (isNonDirectorySeparatorRoot && dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths - pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart + pathPartForUserCheck.search(/[a-zA-Z]\$\//) === 0) { // Dos style nextPart nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1); if (nextDirectorySeparator === -1) { // ignore "//vda1cs4850/c$/folderAtRoot" @@ -125013,7 +125262,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_36 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -125037,9 +125286,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_12 = _loop_36(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_12 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -125108,7 +125357,7 @@ var ts; } function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - var _loop_37 = function (patternText_1) { + var _loop_36 = function (patternText_1) { var pattern = ts.normalizePath(patternText_1); var indexOfStar = pattern.indexOf("*"); // In module resolution, if `pattern` itself has an extension, a file with that extension is looked up directly, @@ -125175,9 +125424,9 @@ var ts; }; for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { var patternText_1 = _a[_i]; - var state_13 = _loop_37(patternText_1); - if (typeof state_13 === "object") - return state_13.value; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } function validateEnding(_a) { @@ -125265,15 +125514,21 @@ var ts; return undefined; } function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { + var normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPaths === undefined) { + return undefined; + } + var normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePaths = ts.flatMap(normalizedSourcePaths, function (sourcePath) { + return ts.map(normalizedTargetPaths, function (targetPath) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName)); }); + }); + var shortest = ts.min(relativePaths, ts.compareNumberOfDirectorySeparators); + if (!shortest) { return undefined; } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs - ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions) - : ts.removeFileExtension(relativePath); + ? removeExtensionAndIndexPostFix(shortest, ending, compilerOptions) + : ts.removeFileExtension(shortest); } function tryGetModuleNameAsNodeModule(_a, _b, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { var path = _a.path, isRedirect = _a.isRedirect; @@ -125410,8 +125665,8 @@ var ts; } } } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { + function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.mapDefined(rootDirs, function (rootDir) { var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath; }); @@ -127979,8 +128234,15 @@ var ts; } if (buildInfo.program) { // If there are pending changes that are not emitted, project is out of date + // When there are syntax errors, changeFileSet will have list of files changed (irrespective of noEmit) + // But in case of semantic error we need special treatment. + // Checking presence of affectedFilesPendingEmit list is fast and good way to tell if there were semantic errors and file emit was blocked + // But if noEmit is true, affectedFilesPendingEmit will have file list even if there are no semantic errors to preserve list of files to be emitted when running with noEmit false + // So with noEmit set to true, check on semantic diagnostics needs to be explicit as oppose to when it is false when only files pending emit is sufficient if (((_a = buildInfo.program.changeFileSet) === null || _a === void 0 ? void 0 : _a.length) || - (!project.options.noEmit && ((_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length))) { + (!project.options.noEmit ? + (_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length : + ts.some(buildInfo.program.semanticDiagnosticsPerFile, ts.isArray))) { return { type: ts.UpToDateStatusType.OutOfDateBuildInfo, buildInfoFile: buildInfoPath @@ -128742,6 +129004,12 @@ var ts; SemanticClassificationFormat["Original"] = "original"; SemanticClassificationFormat["TwentyTwenty"] = "2020"; })(SemanticClassificationFormat = ts.SemanticClassificationFormat || (ts.SemanticClassificationFormat = {})); + var OrganizeImportsMode; + (function (OrganizeImportsMode) { + OrganizeImportsMode["All"] = "All"; + OrganizeImportsMode["SortAndCombine"] = "SortAndCombine"; + OrganizeImportsMode["RemoveUnused"] = "RemoveUnused"; + })(OrganizeImportsMode = ts.OrganizeImportsMode || (ts.OrganizeImportsMode = {})); var CompletionTriggerKind; (function (CompletionTriggerKind) { /** Completion was triggered by typing an identifier, manual invocation (e.g Ctrl+Space) or via API. */ @@ -129787,6 +130055,8 @@ var ts; return lastTypeNode; } function getContextualTypeFromParentOrAncestorTypeNode(node, checker) { + if (node.flags & (8388608 /* NodeFlags.JSDoc */ & ~262144 /* NodeFlags.JavaScriptFile */)) + return undefined; var contextualType = getContextualTypeFromParent(node, checker); if (contextualType) return contextualType; @@ -132273,6 +132543,10 @@ var ts; return jsx === 2 /* JsxEmit.React */ || jsx === 3 /* JsxEmit.ReactNative */; } ts.jsxModeNeedsExplicitImport = jsxModeNeedsExplicitImport; + function isSourceFileFromLibrary(program, node) { + return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); + } + ts.isSourceFileFromLibrary = isSourceFileFromLibrary; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -135299,7 +135573,7 @@ var ts; if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* CompletionKind.MemberLike */ && - isClassLikeMemberCompletion(symbol, location)) { + isClassLikeMemberCompletion(symbol, location, sourceFile)) { var importAdder = void 0; (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken, formatContext), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder, replacementSpan = _b.replacementSpan); sortText = Completions.SortText.ClassMemberSnippets; // sortText has to be lower priority than the sortText for keywords. See #47852. @@ -135371,7 +135645,7 @@ var ts; data: data, }; } - function isClassLikeMemberCompletion(symbol, location) { + function isClassLikeMemberCompletion(symbol, location, sourceFile) { // TODO: support JS files. if (ts.isInJSFile(location)) { return false; @@ -135405,6 +135679,7 @@ var ts; location.parent.parent && ts.isClassElement(location.parent) && location === location.parent.name && + location.parent.getLastToken(sourceFile) === location.parent.name && ts.isClassLike(location.parent.parent)) || (location.parent && ts.isSyntaxList(location) && @@ -142566,6 +142841,12 @@ var ts; var label = ts.getTargetLabel(node.parent, node.text); return label ? [createDefinitionInfoFromName(typeChecker, label, "label" /* ScriptElementKind.label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 } + if (node.kind === 105 /* SyntaxKind.ReturnKeyword */) { + var functionDeclaration = ts.findAncestor(node.parent, function (n) { + return ts.isClassStaticBlockDeclaration(n) ? "quit" : ts.isFunctionLikeDeclaration(n); + }); + return functionDeclaration ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : undefined; + } if (ts.isStaticModifier(node) && ts.isClassStaticBlockDeclaration(node.parent)) { var classDecl = node.parent.parent; var _c = getSymbol(classDecl, typeChecker, stopAtAlias), symbol_1 = _c.symbol, failedAliasResolution_1 = _c.failedAliasResolution; @@ -142701,13 +142982,16 @@ var ts; if (!baseDeclaration) return; var baseTypeNode = ts.getEffectiveBaseTypeNode(baseDeclaration); - var baseType = baseTypeNode ? typeChecker.getTypeAtLocation(baseTypeNode) : undefined; - if (!baseType) + if (!baseTypeNode) + return; + var expression = ts.skipParentheses(baseTypeNode.expression); + var base = ts.isClassExpression(expression) ? expression.symbol : typeChecker.getSymbolAtLocation(expression); + if (!base) return; var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(classElement.name)); var symbol = ts.hasStaticModifier(classElement) - ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbolAtLocation(baseType.symbol, baseDeclaration), name) - : typeChecker.getPropertyOfType(baseType, name); + ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbol(base), name) + : typeChecker.getPropertyOfType(typeChecker.getDeclaredTypeOfSymbol(base), name); if (!symbol) return; return getDefinitionFromSymbol(typeChecker, symbol, node); @@ -143414,19 +143698,24 @@ var ts; return getCommentOwnerInfoWorker(commentOwner.initializer, options); case 260 /* SyntaxKind.ClassDeclaration */: case 261 /* SyntaxKind.InterfaceDeclaration */: - case 168 /* SyntaxKind.PropertySignature */: case 263 /* SyntaxKind.EnumDeclaration */: case 302 /* SyntaxKind.EnumMember */: case 262 /* SyntaxKind.TypeAliasDeclaration */: return { commentOwner: commentOwner }; + case 168 /* SyntaxKind.PropertySignature */: { + var host_1 = commentOwner; + return host_1.type && ts.isFunctionTypeNode(host_1.type) + ? { commentOwner: commentOwner, parameters: host_1.type.parameters, hasReturn: hasReturn(host_1.type, options) } + : { commentOwner: commentOwner }; + } case 240 /* SyntaxKind.VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; - var host_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + var host_2 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } + return host_2 + ? { commentOwner: commentOwner, parameters: host_2.parameters, hasReturn: hasReturn(host_2, options) } : { commentOwner: commentOwner }; } case 308 /* SyntaxKind.SourceFile */: @@ -143456,7 +143745,7 @@ var ts; } function hasReturn(node, options) { return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && - (ts.isArrowFunction(node) && ts.isExpression(node.body) + (ts.isFunctionTypeNode(node) || ts.isArrowFunction(node) && ts.isExpression(node.body) || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { @@ -144497,23 +144786,39 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { + function organizeImports(sourceFile, formatContext, host, program, preferences, mode) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var shouldSort = mode === "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ || mode === "All" /* OrganizeImportsMode.All */; + var shouldCombine = shouldSort; // These are currently inseparable, but I draw a distinction for clarity and in case we add modes in the future. + var shouldRemove = mode === "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */ || mode === "All" /* OrganizeImportsMode.All */; + var maybeRemove = shouldRemove ? removeUnusedImports : ts.identity; + var maybeCoalesce = shouldCombine ? coalesceImports : ts.identity; + var processImportsOfSameModuleSpecifier = function (importGroup) { + var processedDeclarations = maybeCoalesce(maybeRemove(importGroup, sourceFile, program)); + return shouldSort + ? ts.stableSort(processedDeclarations, function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }) + : processedDeclarations; + }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, sourceFile.statements.filter(ts.isImportDeclaration)); - topLevelImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, coalesceAndOrganizeImports); }); - // All of the old ExportDeclarations in the file, in syntactic order. - var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); - organizeImportsWorker(topLevelExportDecls, coalesceExports); + topLevelImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier); }); + // Exports are always used + if (mode !== "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */) { + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); + } for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; if (!ambientModule.body) continue; var ambientModuleImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, ambientModule.body.statements.filter(ts.isImportDeclaration)); - ambientModuleImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, coalesceAndOrganizeImports); }); - var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); - organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + ambientModuleImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier); }); + // Exports are always used + if (mode !== "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */) { + var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + } } return changeTracker.getChanges(); function organizeImportsWorker(oldImportDecls, coalesce) { @@ -144526,8 +144831,12 @@ var ts; // Consider: we could do a more careful check that this trivia is actually a header, // but the consequences of being wrong are very minor. ts.suppressLeadingTrivia(oldImportDecls[0]); - var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); - var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var oldImportGroups = shouldCombine + ? ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }) + : [oldImportDecls]; + var sortedImportGroups = shouldSort + ? ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }) + : oldImportGroups; var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) ? coalesce(importGroup) @@ -144591,11 +144900,7 @@ var ts; } return false; } - function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { - // As a precaution, consider unused import detection to be destructive (GH #43051) - if (skipDestructiveCodeActions) { - return oldImports; - } + function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); @@ -145451,7 +145756,7 @@ var ts; return bestMatch; } function betterMatch(a, b) { - return ts.min(a, b, compareMatches); + return ts.min([a, b], compareMatches); } function compareMatches(a, b) { return a === undefined ? 1 /* Comparison.GreaterThan */ : b === undefined ? -1 /* Comparison.LessThan */ @@ -146060,8 +146365,8 @@ var ts; } if (ts.scanner.getToken() === 15 /* SyntaxKind.TemplateHead */) { var stack = [ts.scanner.getToken()]; - var token = ts.scanner.scan(); loop: while (ts.length(stack)) { + var token = ts.scanner.scan(); switch (token) { case 1 /* SyntaxKind.EndOfFileToken */: break loop; @@ -146089,7 +146394,6 @@ var ts; } break; } - token = ts.scanner.scan(); } nextToken(); } @@ -148568,7 +148872,7 @@ var ts; tags = signature.getJsDocTags(); if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) { documentation = allSignatures[0].getDocumentationComment(typeChecker); - tags = allSignatures[0].getJsDocTags(); + tags = allSignatures[0].getJsDocTags().filter(function (tag) { return tag.name !== "deprecated"; }); // should only include @deprecated JSDoc tag on the first overload (#49368) } } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -148911,7 +149215,7 @@ var ts; return false; } function shouldRescanJsxText(node) { - return ts.isJsxText(node); + return ts.isJsxText(node) || ts.isJsxElement(node) && (lastTokenInfo === null || lastTokenInfo === void 0 ? void 0 : lastTokenInfo.token.kind) === 11 /* SyntaxKind.JsxText */; } function shouldRescanSlashToken(container) { return container.kind === 13 /* SyntaxKind.RegularExpressionLiteral */; @@ -149680,10 +149984,10 @@ var ts; !nodeIsInDecoratorContext(context.nextTokenParent); } function nodeIsInDecoratorContext(node) { - while (ts.isExpressionNode(node)) { + while (node && ts.isExpression(node)) { node = node.parent; } - return node.kind === 167 /* SyntaxKind.Decorator */; + return node && node.kind === 167 /* SyntaxKind.Decorator */; } function isStartOfVariableDeclarationList(context) { return context.currentTokenParent.kind === 258 /* SyntaxKind.VariableDeclarationList */ && @@ -152601,6 +152905,26 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } + function endPositionToDeleteNodeInList(sourceFile, node, prevNode, nextNode) { + var end = startPositionToDeleteNodeInList(sourceFile, nextNode); + if (prevNode === undefined || ts.positionsAreOnSameLine(getAdjustedEndPosition(sourceFile, node, {}), end, sourceFile)) { + return end; + } + var token = ts.findPrecedingToken(nextNode.getStart(sourceFile), sourceFile); + if (isSeparator(node, token)) { + var prevToken = ts.findPrecedingToken(node.getStart(sourceFile), sourceFile); + if (isSeparator(prevNode, prevToken)) { + var pos = ts.skipTrivia(sourceFile.text, token.getEnd(), /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + if (ts.positionsAreOnSameLine(prevToken.getStart(sourceFile), token.getStart(sourceFile), sourceFile)) { + return ts.isLineBreak(sourceFile.text.charCodeAt(pos - 1)) ? pos - 1 : pos; + } + if (ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { + return pos; + } + } + } + return end; + } function getClassOrObjectBraceEnds(cls, sourceFile) { var open = ts.findChildOfKind(cls, 18 /* SyntaxKind.OpenBraceToken */, sourceFile); var close = ts.findChildOfKind(cls, 19 /* SyntaxKind.CloseBraceToken */, sourceFile); @@ -153158,7 +153482,7 @@ var ts; deletedNodesInLists.add(node); changes.deleteRange(sourceFile, { pos: startPositionToDeleteNodeInList(sourceFile, node), - end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : endPositionToDeleteNodeInList(sourceFile, node, containingList[index - 1], containingList[index + 1]), }); } })(textChanges = ts.textChanges || (ts.textChanges = {})); @@ -153628,6 +153952,15 @@ var ts; }); } function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { + if (ts.isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) { + var exprType = checker.getTypeAtLocation(insertionSite); + var asyncIter = checker.getAsyncIterableType(); + if (asyncIter && checker.isTypeAssignableTo(exprType, asyncIter)) { + var forOf = insertionSite.parent; + changeTracker.replaceNode(sourceFile, forOf, ts.factory.updateForOfStatement(forOf, ts.factory.createToken(133 /* SyntaxKind.AwaitKeyword */), forOf.initializer, forOf.expression, forOf.statement)); + return; + } + } if (ts.isBinaryExpression(insertionSite)) { for (var _i = 0, _a = [insertionSite.left, insertionSite.right]; _i < _a.length; _i++) { var side = _a[_i]; @@ -157353,6 +157686,143 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixImportNonExportedMember"; + var errorCodes = [ + ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixId], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program; + var info = getInfo(sourceFile, span.start, program); + if (info === undefined) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, program, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId, ts.Diagnostics.Export_all_referenced_locals)]; + }, + getAllCodeActions: function (context) { + var program = context.program; + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var exports = new ts.Map(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, program); + if (info === undefined) + return undefined; + var exportName = info.exportName, node = info.node, moduleSourceFile = info.moduleSourceFile; + if (tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly) === undefined && ts.canHaveExportModifier(node)) { + changes.insertExportModifier(moduleSourceFile, node); + } + else { + var moduleExports = exports.get(moduleSourceFile) || { typeOnlyExports: [], exports: [] }; + if (exportName.isTypeOnly) { + moduleExports.typeOnlyExports.push(exportName); + } + else { + moduleExports.exports.push(exportName); + } + exports.set(moduleSourceFile, moduleExports); + } + }); + exports.forEach(function (moduleExports, moduleSourceFile) { + var exportDeclaration = tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ true); + if (exportDeclaration && exportDeclaration.isTypeOnly) { + doChanges(changes, program, moduleSourceFile, moduleExports.typeOnlyExports, exportDeclaration); + doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ false)); + } + else { + doChanges(changes, program, moduleSourceFile, __spreadArray(__spreadArray([], moduleExports.exports, true), moduleExports.typeOnlyExports, true), exportDeclaration); + } + }); + })); + } + }); + function getInfo(sourceFile, pos, program) { + var _a; + var token = ts.getTokenAtPosition(sourceFile, pos); + if (ts.isIdentifier(token)) { + var importDeclaration = ts.findAncestor(token, ts.isImportDeclaration); + if (importDeclaration === undefined) + return undefined; + var moduleSpecifier = ts.isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier.text : undefined; + if (moduleSpecifier === undefined) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, moduleSpecifier, /*mode*/ undefined); + if (resolvedModule === undefined) + return undefined; + var moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName); + if (moduleSourceFile === undefined || ts.isSourceFileFromLibrary(program, moduleSourceFile)) + return undefined; + var moduleSymbol = moduleSourceFile.symbol; + var locals = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals; + if (locals === undefined) + return undefined; + var localSymbol = locals.get(token.escapedText); + if (localSymbol === undefined) + return undefined; + var node = getNodeOfSymbol(localSymbol); + if (node === undefined) + return undefined; + var exportName = { node: token, isTypeOnly: ts.isTypeDeclaration(node) }; + return { exportName: exportName, node: node, moduleSourceFile: moduleSourceFile, moduleSpecifier: moduleSpecifier }; + } + return undefined; + } + function doChange(changes, program, _a) { + var exportName = _a.exportName, node = _a.node, moduleSourceFile = _a.moduleSourceFile; + var exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); + if (exportDeclaration) { + updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]); + } + else if (ts.canHaveExportModifier(node)) { + changes.insertExportModifier(moduleSourceFile, node); + } + else { + createExport(changes, program, moduleSourceFile, [exportName]); + } + } + function doChanges(changes, program, sourceFile, moduleExports, node) { + if (ts.length(moduleExports)) { + if (node) { + updateExport(changes, program, sourceFile, node, moduleExports); + } + else { + createExport(changes, program, sourceFile, moduleExports); + } + } + } + function tryGetExportDeclaration(sourceFile, isTypeOnly) { + var predicate = function (node) { + return ts.isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); + }; + return ts.findLast(sourceFile.statements, predicate); + } + function updateExport(changes, program, sourceFile, node, names) { + var namedExports = node.exportClause && ts.isNamedExports(node.exportClause) ? node.exportClause.elements : ts.factory.createNodeArray([]); + var allowTypeModifier = !node.isTypeOnly && !!(program.getCompilerOptions().isolatedModules || ts.find(namedExports, function (e) { return e.isTypeOnly; })); + changes.replaceNode(sourceFile, node, ts.factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, ts.factory.createNamedExports(ts.factory.createNodeArray(__spreadArray(__spreadArray([], namedExports, true), createExportSpecifiers(names, allowTypeModifier), true), /*hasTrailingComma*/ namedExports.hasTrailingComma)), node.moduleSpecifier, node.assertClause)); + } + function createExport(changes, program, sourceFile, names) { + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ !!program.getCompilerOptions().isolatedModules)), /*moduleSpecifier*/ undefined, /*assertClause*/ undefined)); + } + function createExportSpecifiers(names, allowTypeModifier) { + return ts.factory.createNodeArray(ts.map(names, function (n) { return ts.factory.createExportSpecifier(allowTypeModifier && n.isTypeOnly, /*propertyName*/ undefined, n.node); })); + } + function getNodeOfSymbol(symbol) { + if (symbol.valueDeclaration === undefined) { + return ts.firstOrUndefined(symbol.declarations); + } + var declaration = symbol.valueDeclaration; + var variableStatement = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : undefined; + return variableStatement && ts.length(variableStatement.declarationList.declarations) === 1 ? variableStatement : declaration; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -157883,7 +158353,7 @@ var ts; var argIndex = ts.findIndex(parent.parent.arguments, function (arg) { return arg === parent; }); if (argIndex < 0) return undefined; - var signature = ts.singleOrUndefined(checker.getSignaturesOfType(checker.getTypeAtLocation(parent.parent.expression), 0 /* SignatureKind.Call */)); + var signature = checker.getResolvedSignature(parent.parent); if (!(signature && signature.declaration && signature.parameters[argIndex])) return undefined; var param = signature.parameters[argIndex].valueDeclaration; @@ -157930,13 +158400,13 @@ var ts; if (ts.isIdentifier(token) && ts.isCallExpression(parent.parent)) { var moduleDeclaration = ts.find(symbol.declarations, ts.isModuleDeclaration); var moduleDeclarationSourceFile = moduleDeclaration === null || moduleDeclaration === void 0 ? void 0 : moduleDeclaration.getSourceFile(); - if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { + if (moduleDeclaration && moduleDeclarationSourceFile && !ts.isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { return { kind: InfoKind.Function, token: token, call: parent.parent, sourceFile: sourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleDeclaration }; } var moduleSourceFile = ts.find(symbol.declarations, ts.isSourceFile); if (sourceFile.commonJsModuleIndicator) return undefined; - if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) { + if (moduleSourceFile && !ts.isSourceFileFromLibrary(program, moduleSourceFile)) { return { kind: InfoKind.Function, token: token, call: parent.parent, sourceFile: moduleSourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleSourceFile }; } } @@ -157946,7 +158416,7 @@ var ts; return undefined; // Prefer to change the class instead of the interface if they are merged var declaration = classDeclaration || ts.find(symbol.declarations, function (d) { return ts.isInterfaceDeclaration(d) || ts.isTypeLiteralNode(d); }); - if (declaration && !isSourceFileFromLibrary(program, declaration.getSourceFile())) { + if (declaration && !ts.isSourceFileFromLibrary(program, declaration.getSourceFile())) { var makeStatic = !ts.isTypeLiteralNode(declaration) && (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); if (makeStatic && (ts.isPrivateIdentifier(token) || ts.isInterfaceDeclaration(declaration))) return undefined; @@ -157958,14 +158428,11 @@ var ts; return { kind: InfoKind.TypeLikeDeclaration, token: token, call: call, modifierFlags: modifierFlags, parentDeclaration: declaration, declSourceFile: declSourceFile, isJSFile: isJSFile }; } var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); - if (enumDeclaration && !(leftExpressionType.flags & 1056 /* TypeFlags.EnumLike */) && !ts.isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { + if (enumDeclaration && !(leftExpressionType.flags & 1056 /* TypeFlags.EnumLike */) && !ts.isPrivateIdentifier(token) && !ts.isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { return { kind: InfoKind.Enum, token: token, parentDeclaration: enumDeclaration }; } return undefined; } - function isSourceFileFromLibrary(program, node) { - return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); - } function getActionsForMissingMemberDeclaration(context, info) { return info.isJSFile ? ts.singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : createActionsForAddMissingMemberInTypeScriptFile(context, info); @@ -163391,8 +163858,8 @@ var ts; var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; - var description = functionExtraction.description; if (refactor.refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + var description = functionExtraction.description; if (functionExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will @@ -163416,15 +163883,15 @@ var ts; } } if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + var description = constantExtraction.description; if (constantExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will // preferentially go into nearer scopes - var description_1 = constantExtraction.description; - if (!usedConstantNames.has(description_1)) { - usedConstantNames.set(description_1, true); + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); constantActions.push({ - description: description_1, + description: description, name: "constant_scope_".concat(i), kind: extractConstantAction.kind }); @@ -163569,7 +164036,6 @@ var ts; var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, adjustedSpan); // Do the same for the ending position var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, adjustedSpan); - var declarations = []; // We'll modify these flags as we walk the tree to collect data // about what things need to be done as part of the extraction. var rangeFacts = RangeFacts.None; @@ -163612,7 +164078,7 @@ var ts; // the expression. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } - return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations, thisNode: thisNode } }; + return { targetRange: { range: statements, facts: rangeFacts, thisNode: thisNode } }; } if (ts.isReturnStatement(start) && !start.expression) { // Makes no sense to extract an expression-less return statement. @@ -163624,7 +164090,7 @@ var ts; if (errors) { return { errors: errors }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations, thisNode: thisNode } }; // TODO: GH#18217 + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode: thisNode } }; // TODO: GH#18217 /** * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. * @param node The unrefined extraction node. @@ -163636,10 +164102,10 @@ var ts; } } else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { - var declarations_6 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; + var declarations = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, declarations_5 = declarations_6; _i < declarations_5.length; _i++) { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; if (declaration.initializer) { numInitializers++; @@ -163739,7 +164205,6 @@ var ts; (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } - declarations.push(node.symbol); } // Some things can't be extracted in certain situations switch (node.kind) { @@ -165464,7 +165929,7 @@ var ts; function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); var prologueDirectives = ts.takeWhile(oldFile.statements, ts.isPrologueDirective); - if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + if (oldFile.externalModuleIndicator === undefined && oldFile.commonJsModuleIndicator === undefined && usage.oldImportsNeededByNewFile.size() === 0) { deleteMovedStatements(oldFile, toMove.ranges, changes); return __spreadArray(__spreadArray([], prologueDirectives, true), toMove.all, true); } @@ -165705,7 +166170,12 @@ var ts; switch (name.kind) { case 79 /* SyntaxKind.Identifier */: if (isUnused(name)) { - changes.delete(sourceFile, name); + if (varDecl.initializer && ts.isRequireCall(varDecl.initializer, /*requireStringLiteralLikeArgument*/ true)) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && ts.length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); + } + else { + changes.delete(sourceFile, name); + } } break; case 204 /* SyntaxKind.ArrayBindingPattern */: @@ -165937,6 +166407,9 @@ var ts; ts.copyEntries(this.map, clone.map); return clone; }; + SymbolSet.prototype.size = function () { + return this.map.size; + }; return SymbolSet; }()); function isTopLevelDeclaration(node) { @@ -166025,7 +166498,8 @@ var ts; if (useEs6Exports) { return !ts.isExpressionStatement(decl) && ts.hasSyntacticModifier(decl, 1 /* ModifierFlags.Export */) || !!(name && ((_a = sourceFile.symbol.exports) === null || _a === void 0 ? void 0 : _a.has(name.escapedText))); } - return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + return !!sourceFile.symbol && !!sourceFile.symbol.exports && + getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); } function addExport(decl, useEs6Exports) { return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); @@ -167785,8 +168259,8 @@ var ts; tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); } }; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; _loop_20(declaration); } } @@ -167812,8 +168286,8 @@ var ts; if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); }; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; _loop_21(declaration); } } @@ -168983,12 +169457,14 @@ var ts; return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } function organizeImports(args, formatOptions, preferences) { + var _a; if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(args.type === "file"); var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); + var mode = (_a = args.mode) !== null && _a !== void 0 ? _a : (args.skipDestructiveCodeActions ? "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ : "All" /* OrganizeImportsMode.All */); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, mode); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -171987,6 +172463,12 @@ var ts; CommandTypes["ProvideInlayHints"] = "provideInlayHints"; // NOTE: If updating this, be sure to also update `allCommandNames` in `testRunner/unittests/tsserver/session.ts`. })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {})); + var OrganizeImportsMode; + (function (OrganizeImportsMode) { + OrganizeImportsMode["All"] = "All"; + OrganizeImportsMode["SortAndCombine"] = "SortAndCombine"; + OrganizeImportsMode["RemoveUnused"] = "RemoveUnused"; + })(OrganizeImportsMode = protocol.OrganizeImportsMode || (protocol.OrganizeImportsMode = {})); var WatchFileKind; (function (WatchFileKind) { WatchFileKind["FixedPollingInterval"] = "FixedPollingInterval"; @@ -172873,6 +173355,7 @@ var ts; this.watchOptions = watchOptions; this.rootFiles = []; this.rootFilesMap = new ts.Map(); + /*@internal*/ this.plugins = []; /*@internal*/ /** @@ -173401,6 +173884,7 @@ var ts; this.directoryStructureHost = undefined; this.exportMapCache = undefined; this.projectErrors = undefined; + this.plugins.length = 0; // Clean up file watchers waiting for missing files if (this.missingFilesMap) { ts.clearMap(this.missingFilesMap, ts.closeFileWatcher); @@ -174074,35 +174558,39 @@ var ts; Project.prototype.isSourceOfProjectReferenceRedirect = function (fileName) { return !!this.program && this.program.isSourceOfProjectReferenceRedirect(fileName); }; + /*@internal*/ + Project.prototype.getGlobalPluginSearchPaths = function () { + // Search any globally-specified probe paths, then our peer node_modules + return __spreadArray(__spreadArray([], this.projectService.pluginProbeLocations, true), [ + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + ts.combinePaths(this.projectService.getExecutingFilePath(), "../../.."), + ], false); + }; Project.prototype.enableGlobalPlugins = function (options, pluginConfigOverrides) { + if (!this.projectService.globalPlugins.length) + return; var host = this.projectService.host; if (!host.require && !host.importPlugin) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } - // Search any globally-specified probe paths, then our peer node_modules - var searchPaths = __spreadArray(__spreadArray([], this.projectService.pluginProbeLocations, true), [ - // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ - ts.combinePaths(this.projectService.getExecutingFilePath(), "../../.."), - ], false); - if (this.projectService.globalPlugins) { - var _loop_1 = function (globalPluginName) { - // Skip empty names from odd commandline parses - if (!globalPluginName) - return "continue"; - // Skip already-locally-loaded plugins - if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) - return "continue"; - // Provide global: true so plugins can detect why they can't find their config - this_1.projectService.logger.info("Loading global plugin ".concat(globalPluginName)); - this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides); - }; - var this_1 = this; - // Enable global plugins with synthetic configuration entries - for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { - var globalPluginName = _a[_i]; - _loop_1(globalPluginName); - } + // Enable global plugins with synthetic configuration entries + var searchPaths = this.getGlobalPluginSearchPaths(); + var _loop_1 = function (globalPluginName) { + // Skip empty names from odd commandline parses + if (!globalPluginName) + return "continue"; + // Skip already-locally-loaded plugins + if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) + return "continue"; + // Provide global: true so plugins can detect why they can't find their config + this_1.projectService.logger.info("Loading global plugin ".concat(globalPluginName)); + this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides); + }; + var this_1 = this; + for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { + var globalPluginName = _a[_i]; + _loop_1(globalPluginName); } }; /** @@ -174833,14 +175321,16 @@ var ts; }; /*@internal*/ ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) { + var _a; + this.plugins.length = 0; + if (!((_a = options.plugins) === null || _a === void 0 ? void 0 : _a.length) && !this.projectService.globalPlugins.length) + return; var host = this.projectService.host; if (!host.require && !host.importPlugin) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } - // Search our peer node_modules, then any globally-specified probe paths - // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ - var searchPaths = __spreadArray([ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")], this.projectService.pluginProbeLocations, true); + var searchPaths = this.getGlobalPluginSearchPaths(); if (this.projectService.allowLocalPluginLoads) { var local = ts.getDirectoryPath(this.canonicalConfigFilePath); this.projectService.logger.info("Local plugin loading enabled; adding ".concat(local, " to search paths")); @@ -174848,8 +175338,8 @@ var ts; } // Enable tsconfig-specified plugins if (options.plugins) { - for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { - var pluginConfigEntry = _a[_i]; + for (var _i = 0, _b = options.plugins; _i < _b.length; _i++) { + var pluginConfigEntry = _b[_i]; this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); } } @@ -175694,18 +176184,20 @@ var ts; return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName); }; /* @internal */ - ProjectService.prototype.tryGetDefaultProjectForFile = function (fileName) { - var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + ProjectService.prototype.tryGetDefaultProjectForFile = function (fileNameOrScriptInfo) { + var scriptInfo = ts.isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined; }; /* @internal */ - ProjectService.prototype.ensureDefaultProjectForFile = function (fileName) { - return this.tryGetDefaultProjectForFile(fileName) || this.doEnsureDefaultProjectForFile(fileName); + ProjectService.prototype.ensureDefaultProjectForFile = function (fileNameOrScriptInfo) { + return this.tryGetDefaultProjectForFile(fileNameOrScriptInfo) || this.doEnsureDefaultProjectForFile(fileNameOrScriptInfo); }; - ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileName) { + ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileNameOrScriptInfo) { this.ensureProjectStructuresUptoDate(); - var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(fileName), server.Errors.ThrowNoProject()); + var scriptInfo = ts.isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; + return scriptInfo ? + scriptInfo.getDefaultProject() : + (this.logErrorForScriptInfoNotFound(ts.isString(fileNameOrScriptInfo) ? fileNameOrScriptInfo : fileNameOrScriptInfo.fileName), server.Errors.ThrowNoProject()); }; ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { this.ensureProjectStructuresUptoDate(); @@ -177877,7 +178369,7 @@ var ts; if (this.serverMode !== ts.LanguageServiceMode.Semantic || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { return; } - var project = scriptInfo.getDefaultProject(); + var project = this.ensureDefaultProjectForFile(scriptInfo); if (!project.languageServiceEnabled) { return; } @@ -180477,6 +180969,10 @@ var ts; this.projectService.logErrorForScriptInfoNotFound(args.file); return server.Errors.ThrowNoProject(); } + else if (!getScriptInfoEnsuringProjectsUptoDate) { + // Ensure there are containing projects are present + this.projectService.ensureDefaultProjectForFile(scriptInfo); + } projects = scriptInfo.containingProjects; symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); } @@ -180545,6 +181041,7 @@ var ts; var references = getReferencesWorker(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, this.logger); if (!simplifiedResult) return references; + var preferences = this.getPreferences(file); var defaultProject = this.getDefaultProject(args); var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); @@ -180553,7 +181050,7 @@ var ts; var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; var symbolName = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; var refs = ts.flatMap(references, function (referencedSymbol) { - return referencedSymbol.references.map(function (entry) { return referenceEntryToReferencesResponseItem(_this.projectService, entry); }); + return referencedSymbol.references.map(function (entry) { return referenceEntryToReferencesResponseItem(_this.projectService, entry, preferences); }); }); return { refs: refs, symbolName: symbolName, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; }; @@ -180561,6 +181058,7 @@ var ts; var _this = this; var projects = this.getProjects(args); var fileName = args.file; + var preferences = this.getPreferences(server.toNormalizedPath(fileName)); var references = []; var seen = createDocumentSpanSet(); forEachProjectInProjects(projects, /*path*/ undefined, function (project) { @@ -180579,7 +181077,7 @@ var ts; }); if (!simplifiedResult) return references; - var refs = references.map(function (entry) { return referenceEntryToReferencesResponseItem(_this.projectService, entry); }); + var refs = references.map(function (entry) { return referenceEntryToReferencesResponseItem(_this.projectService, entry, preferences); }); return { refs: refs, symbolName: "\"".concat(args.file, "\"") @@ -180603,13 +181101,7 @@ var ts; return this.getFileAndProjectWorker(args.file, args.projectFileName); }; Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) { - // Since this is syntactic operation, there should always be project for the file - // throw if we dont get project - var file = server.toNormalizedPath(args.file); - var project = this.getProject(args.projectFileName) || this.projectService.ensureDefaultProjectForFile(file); - if (!project) { - return server.Errors.ThrowNoProject(); - } + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; return { file: file, languageService: project.getLanguageService(/*ensureSynchronized*/ false) @@ -181150,11 +181642,12 @@ var ts; } }; Session.prototype.organizeImports = function (args, simplifiedResult) { + var _a; ts.Debug.assert(args.scope.type === "file"); - var _a = this.getFileAndProject(args.scope.args), file = _a.file, project = _a.project; + var _b = this.getFileAndProject(args.scope.args), file = _b.file, project = _b.project; var changes = project.getLanguageService().organizeImports({ fileName: file, - skipDestructiveCodeActions: args.skipDestructiveCodeActions, + mode: (_a = args.mode) !== null && _a !== void 0 ? _a : (args.skipDestructiveCodeActions ? "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ : undefined), type: "file", }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { @@ -181648,14 +182141,18 @@ var ts; } return text; } - function referenceEntryToReferencesResponseItem(projectService, _a) { + function referenceEntryToReferencesResponseItem(projectService, _a, _b) { var fileName = _a.fileName, textSpan = _a.textSpan, contextSpan = _a.contextSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition; + var disableLineTextInReferences = _b.disableLineTextInReferences; var scriptInfo = ts.Debug.checkDefined(projectService.getScriptInfo(fileName)); var span = toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo); - var lineSpan = scriptInfo.lineToTextSpan(span.start.line - 1); - var lineText = scriptInfo.getSnapshot().getText(lineSpan.start, ts.textSpanEnd(lineSpan)).replace(/\r|\n/g, ""); + var lineText = disableLineTextInReferences ? undefined : getLineText(scriptInfo, span); return __assign(__assign({ file: fileName }, span), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition }); } + function getLineText(scriptInfo, span) { + var lineSpan = scriptInfo.lineToTextSpan(span.start.line - 1); + return scriptInfo.getSnapshot().getText(lineSpan.start, ts.textSpanEnd(lineSpan)).replace(/\r|\n/g, ""); + } function isCompletionEntryData(data) { return data === undefined || data && typeof data === "object" && typeof data.exportName === "string" @@ -185695,6 +186192,9 @@ var ts; process.on("message", function (e) { _this.onMessage(e); }); + process.on("disconnect", function () { + _this.exit(); + }); }; return IpcIOSession; }(IOSession)); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 575116ceed587..90dd9ed780fd0 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -5399,9 +5399,9 @@ declare namespace ts { /** If provided, called with Diagnostic message that informs about change in watch status */ onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions, errorCount?: number): void; /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: CompilerOptions): FileWatcher; + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: CompilerOptions): FileWatcher; + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; /** If provided, will be used to reset existing delayed compilation */ @@ -6032,8 +6032,15 @@ declare namespace ts { type: "file"; fileName: string; } + enum OrganizeImportsMode { + All = "All", + SortAndCombine = "SortAndCombine", + RemoveUnused = "RemoveUnused" + } interface OrganizeImportsArgs extends CombinedCodeFixScope { + /** @deprecated Use `mode` instead */ skipDestructiveCodeActions?: boolean; + mode?: OrganizeImportsMode; } type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; enum CompletionTriggerKind { @@ -7616,9 +7623,16 @@ declare namespace ts.server.protocol { arguments: OrganizeImportsRequestArgs; } type OrganizeImportsScope = GetCombinedCodeFixScope; + enum OrganizeImportsMode { + All = "All", + SortAndCombine = "SortAndCombine", + RemoveUnused = "RemoveUnused" + } interface OrganizeImportsRequestArgs { scope: OrganizeImportsScope; + /** @deprecated Use `mode` instead */ skipDestructiveCodeActions?: boolean; + mode?: OrganizeImportsMode; } interface OrganizeImportsResponse extends Response { body: readonly FileCodeEdits[]; @@ -7968,12 +7982,14 @@ declare namespace ts.server.protocol { command: CommandTypes.References; } interface ReferencesResponseItem extends FileSpanWithContext { - /** Text of line containing the reference. Including this - * with the response avoids latency of editor loading files - * to show text of reference line (the server already has - * loaded the referencing files). + /** + * Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has loaded the referencing files). + * + * If {@link UserPreferences.disableLineTextInReferences} is enabled, the property won't be filled */ - lineText: string; + lineText?: string; /** * True if reference is a write location, false otherwise. */ @@ -9819,6 +9835,10 @@ declare namespace ts.server.protocol { readonly includeInlayFunctionLikeReturnTypeHints?: boolean; readonly includeInlayEnumMemberValueHints?: boolean; readonly autoImportFileExcludePatterns?: string[]; + /** + * Indicates whether {@link ReferencesResponseItem.lineText} is supported. + */ + readonly disableLineTextInReferences?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -10070,7 +10090,6 @@ declare namespace ts.server { private externalFiles; private missingFilesMap; private generatedFilesMap; - private plugins; protected languageService: LanguageService; languageServiceEnabled: boolean; readonly trace?: (s: string) => void; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 00143e7aea26d..1affbcf305f17 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -108,7 +108,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 = "".concat(ts.versionMajorMinor, ".1-beta"); + ts.version = "".concat(ts.versionMajorMinor, ".2-rc"); /* @internal */ var Comparison; (function (Comparison) { @@ -1900,8 +1900,8 @@ var ts; return compareValues(a === null || a === void 0 ? void 0 : a.start, b === null || b === void 0 ? void 0 : b.start) || compareValues(a === null || a === void 0 ? void 0 : a.length, b === null || b === void 0 ? void 0 : b.length); } ts.compareTextSpans = compareTextSpans; - function min(a, b, compare) { - return compare(a, b) === -1 /* Comparison.LessThan */ ? a : b; + function min(items, compare) { + return reduceLeft(items, function (x, y) { return compare(x, y) === -1 /* Comparison.LessThan */ ? x : y; }); } ts.min = min; /** @@ -3214,11 +3214,13 @@ var ts; // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers // > MUST NOT include leading zeroes. var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; // https://semver.org/#spec-item-10 // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated // > identifiers immediately following the patch or pre-release version. Identifiers MUST // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var buildPartRegExp = /^[a-z0-9-]+$/i; // https://semver.org/#spec-item-9 // > Numeric identifiers MUST NOT include leading zeroes. var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; @@ -3238,13 +3240,15 @@ var ts; ts.Debug.assert(major >= 0, "Invalid argument: major"); ts.Debug.assert(minor >= 0, "Invalid argument: minor"); ts.Debug.assert(patch >= 0, "Invalid argument: patch"); - ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); - ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + var prereleaseArray = prerelease ? ts.isArray(prerelease) ? prerelease : prerelease.split(".") : ts.emptyArray; + var buildArray = build ? ts.isArray(build) ? build : build.split(".") : ts.emptyArray; + ts.Debug.assert(ts.every(prereleaseArray, function (s) { return prereleasePartRegExp.test(s); }), "Invalid argument: prerelease"); + ts.Debug.assert(ts.every(buildArray, function (s) { return buildPartRegExp.test(s); }), "Invalid argument: build"); this.major = major; this.minor = minor; this.patch = patch; - this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; - this.build = build ? build.split(".") : ts.emptyArray; + this.prerelease = prereleaseArray; + this.build = buildArray; } Version.tryParse = function (text) { var result = tryParseComponents(text); @@ -3283,6 +3287,10 @@ var ts; default: return ts.Debug.assertNever(field); } }; + Version.prototype.with = function (fields) { + var _a = fields.major, major = _a === void 0 ? this.major : _a, _b = fields.minor, minor = _b === void 0 ? this.minor : _b, _c = fields.patch, patch = _c === void 0 ? this.patch : _c, _d = fields.prerelease, prerelease = _d === void 0 ? this.prerelease : _d, _e = fields.build, build = _e === void 0 ? this.build : _e; + return new Version(major, minor, patch, prerelease, build); + }; Version.prototype.toString = function () { var result = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); if (ts.some(this.prerelease)) @@ -3291,7 +3299,7 @@ var ts; result += "+".concat(this.build.join(".")); return result; }; - Version.zero = new Version(0, 0, 0); + Version.zero = new Version(0, 0, 0, ["0"]); return Version; }()); ts.Version = Version; @@ -3374,6 +3382,10 @@ var ts; } return undefined; }; + /** + * Tests whether a version matches the range. This is equivalent to `satisfies(version, range, { includePrerelease: true })`. + * in `node-semver`. + */ VersionRange.prototype.test = function (version) { if (typeof version === "string") version = new Version(version); @@ -3484,19 +3496,20 @@ var ts; break; case "<": case ">=": - comparators.push(createComparator(operator, version)); + comparators.push(isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version.with({ prerelease: "0" })) : + createComparator(operator, version)); break; case "<=": case ">": - comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : - isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major").with({ prerelease: "0" })) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor").with({ prerelease: "0" })) : createComparator(operator, version)); break; case "=": case undefined: if (isWildcard(minor) || isWildcard(patch)) { - comparators.push(createComparator(">=", version)); - comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + comparators.push(createComparator(">=", version.with({ prerelease: "0" }))); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor").with({ prerelease: "0" }))); } else { comparators.push(createComparator("=", version)); @@ -5105,8 +5118,8 @@ var ts; NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAccessInAsync"] = 2048] = "MethodWithSuperPropertyAccessInAsync"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAssignmentInAsync"] = 4096] = "MethodWithSuperPropertyAssignmentInAsync"; NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; @@ -6741,7 +6754,7 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; + var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; var pollingWatches = new ts.Map(); var fsWatches = new ts.Map(); var fsWatchesRecursive = new ts.Map(); @@ -6807,8 +6820,8 @@ var ts; return useNonPollingWatchers ? // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : - // Default to do not use fixed polling interval - { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.UseFsEvents }; + // Default to using fs events + { watchFile: ts.WatchFileKind.UseFsEvents }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -7080,7 +7093,6 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, - defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, inodeWatching: isLinuxOrMacOs, sysLog: sysLog, }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; @@ -9591,6 +9603,10 @@ var ts; Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted: diag(6399, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399", "Project '{0}' is out of date because buildinfo file '{1}' indicates that some of the changes were not emitted"), Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files: diag(6400, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400", "Project '{0}' is up to date but needs to update timestamps of output files that are older than input files"), Project_0_is_out_of_date_because_there_was_error_reading_file_1: diag(6401, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401", "Project '{0}' is out of date because there was error reading file '{1}'"), + Resolving_in_0_mode_with_conditions_1: diag(6402, ts.DiagnosticCategory.Message, "Resolving_in_0_mode_with_conditions_1_6402", "Resolving in {0} mode with conditions {1}."), + Matched_0_condition_1: diag(6403, ts.DiagnosticCategory.Message, "Matched_0_condition_1_6403", "Matched '{0}' condition '{1}'."), + Using_0_subpath_1_with_target_2: diag(6404, ts.DiagnosticCategory.Message, "Using_0_subpath_1_with_target_2_6404", "Using '{0}' subpath '{1}' with target '{2}'."), + Saw_non_matching_condition_0: diag(6405, ts.DiagnosticCategory.Message, "Saw_non_matching_condition_0_6405", "Saw non-matching condition '{0}'."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -9907,6 +9923,8 @@ var ts; Remove_type_from_import_of_0_from_1: diag(90056, ts.DiagnosticCategory.Message, "Remove_type_from_import_of_0_from_1_90056", "Remove 'type' from import of '{0}' from \"{1}\""), Add_import_from_0: diag(90057, ts.DiagnosticCategory.Message, "Add_import_from_0_90057", "Add import from \"{0}\""), Update_import_from_0: diag(90058, ts.DiagnosticCategory.Message, "Update_import_from_0_90058", "Update import from \"{0}\""), + Export_0_from_module_1: diag(90059, ts.DiagnosticCategory.Message, "Export_0_from_module_1_90059", "Export '{0}' from module '{1}'"), + Export_all_referenced_locals: diag(90060, ts.DiagnosticCategory.Message, "Export_all_referenced_locals_90060", "Export all referenced locals"), 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}"), @@ -11364,7 +11382,7 @@ var ts; return -1; } function peekExtendedUnicodeEscape() { - if (languageVersion >= 2 /* ScriptTarget.ES2015 */ && codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { + if (codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { var start_2 = pos; pos += 3; var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); @@ -21667,6 +21685,32 @@ var ts; return parameter.kind === 343 /* SyntaxKind.JSDocParameterTag */ ? (_a = parameter.typeExpression) === null || _a === void 0 ? void 0 : _a.type : parameter.type; } ts.getParameterTypeNode = getParameterTypeNode; + function isTypeDeclaration(node) { + switch (node.kind) { + case 165 /* SyntaxKind.TypeParameter */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: + return true; + case 270 /* SyntaxKind.ImportClause */: + return node.isTypeOnly; + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: + return node.parent.parent.isTypeOnly; + default: + return false; + } + } + ts.isTypeDeclaration = isTypeDeclaration; + function canHaveExportModifier(node) { + return ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) || isTypeDeclaration(node) || (ts.isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node)); + } + ts.canHaveExportModifier = canHaveExportModifier; })(ts || (ts = {})); /* @internal */ var ts; @@ -21675,13 +21719,11 @@ var ts; * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator. */ function createBaseNodeFactory() { - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name return { createBaseSourceFileNode: createBaseSourceFileNode, createBaseIdentifierNode: createBaseIdentifierNode, @@ -23145,7 +23187,7 @@ var ts; return node; } // @api - function createIdentifier(text, typeArguments, originalKeywordKind) { + function createIdentifier(text, typeArguments, originalKeywordKind, hasExtendedUnicodeEscape) { var node = createBaseIdentifier(text, originalKeywordKind); if (typeArguments) { // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations @@ -23154,6 +23196,10 @@ var ts; if (node.originalKeywordKind === 133 /* SyntaxKind.AwaitKeyword */) { node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } + if (hasExtendedUnicodeEscape) { + node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + } return node; } // @api @@ -27609,11 +27655,9 @@ var ts; rawTextScanner.setText("`" + rawText + "`"); break; case 15 /* SyntaxKind.TemplateHead */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("`" + rawText + "${"); break; case 16 /* SyntaxKind.TemplateMiddle */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("}" + rawText + "${"); break; case 17 /* SyntaxKind.TemplateTail */: @@ -27972,7 +28016,6 @@ var ts; return node; } ts.createInputFiles = createInputFiles; - // tslint:disable-next-line variable-name var SourceMapSource; /** * Create an external source map source file reference @@ -28764,6 +28807,8 @@ var ts; // - The verb (`next`, `throw`, or `return` method) to delegate to the expression // of a `yield*`. // - The result of evaluating the verb delegated to the expression of a `yield*`. + // g A temporary variable that holds onto the generator object until the generator + // is started, allowing it to also act as the `suspendedStart` state. // // functions: // verb(n) Creates a bound callback to the `step` function for opcode `n`. @@ -28802,7 +28847,7 @@ var ts; importName: "__generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; // ES Module Helpers ts.createBindingHelper = { @@ -32106,13 +32151,11 @@ var ts; var scanner = ts.createScanner(99 /* ScriptTarget.Latest */, /*skipTrivia*/ true); var disallowInAndDecoratorContext = 4096 /* NodeFlags.DisallowInContext */ | 16384 /* NodeFlags.DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name function countNode(node) { nodeCount++; return node; @@ -33088,8 +33131,9 @@ var ts; // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); var text = internIdentifier(scanner.getTokenValue()); + var hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape(); nextTokenWithoutCheck(); - return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos); + return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind, hasExtendedUnicodeEscape), pos); } if (token() === 80 /* SyntaxKind.PrivateIdentifier */) { parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); @@ -42228,12 +42272,23 @@ var ts; } function writeConfigurations() { // Filter applicable options to place in the file - var categorizedOptions = ts.createMultiMap(); + var categorizedOptions = new ts.Map(); + // Set allowed categories in order + categorizedOptions.set(ts.Diagnostics.Projects, []); + categorizedOptions.set(ts.Diagnostics.Language_and_Environment, []); + categorizedOptions.set(ts.Diagnostics.Modules, []); + categorizedOptions.set(ts.Diagnostics.JavaScript_Support, []); + categorizedOptions.set(ts.Diagnostics.Emit, []); + categorizedOptions.set(ts.Diagnostics.Interop_Constraints, []); + categorizedOptions.set(ts.Diagnostics.Type_Checking, []); + categorizedOptions.set(ts.Diagnostics.Completeness, []); for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { var option = optionDeclarations_1[_i]; - var category = option.category; if (isAllowedOptionForOutput(option)) { - categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + var listForCategory = categorizedOptions.get(option.category); + if (!listForCategory) + categorizedOptions.set(option.category, listForCategory = []); + listForCategory.push(option); } } // Serialize all options and their descriptions @@ -42244,7 +42299,7 @@ var ts; if (entries.length !== 0) { entries.push({ value: "" }); } - entries.push({ value: "/* ".concat(category, " */") }); + entries.push({ value: "/* ".concat(ts.getLocaleSpecificMessage(category), " */") }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -44286,6 +44341,9 @@ var ts; requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; + if (traceEnabled && ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) <= ts.ModuleResolutionKind.NodeNext) { + trace(host, ts.Diagnostics.Resolving_in_0_mode_with_conditions_1, features & NodeResolutionFeatures.EsmMode ? "ESM" : "CJS", conditions.map(function (c) { return "'".concat(c, "'"); }).join(", ")); + } var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { @@ -44875,7 +44933,7 @@ var ts; } if (mainExport) { var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false); - return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false, "."); } } else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) { @@ -44955,7 +45013,7 @@ var ts; var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!ts.endsWith(moduleName, ts.directorySeparator) && moduleName.indexOf("*") === -1 && ts.hasProperty(lookupTable, moduleName)) { var target = lookupTable[moduleName]; - return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName); } var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), comparePatternKeys); for (var _i = 0, expandingKeys_1 = expandingKeys; _i < expandingKeys_1.length; _i++) { @@ -44964,17 +45022,17 @@ var ts; var target = lookupTable[potentialTarget]; var starPos = potentialTarget.indexOf("*"); var subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.endsWith(potentialTarget, "*") && ts.startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length - 1); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.startsWith(moduleName, potentialTarget)) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false, potentialTarget); } } function matchesPatternWithTrailer(target, name) { @@ -44991,7 +45049,7 @@ var ts; */ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) { return loadModuleFromTargetImportOrExport; - function loadModuleFromTargetImportOrExport(target, subpath, pattern) { + function loadModuleFromTargetImportOrExport(target, subpath, pattern, key) { if (typeof target === "string") { if (!pattern && subpath.length > 0 && !ts.endsWith(target, "/")) { if (state.traceEnabled) { @@ -45002,6 +45060,8 @@ var ts; if (!ts.startsWith(target, "./")) { if (isImports && !ts.startsWith(target, "../") && !ts.startsWith(target, "/") && !ts.isRootedDiskPath(target)) { var combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath; + traceIfEnabled(state, ts.Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup); + traceIfEnabled(state, ts.Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/"); var result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, [extensions], redirectedReference); return toSearchResult(result.resolvedModule ? { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId, originalPath: result.resolvedModule.originalPath } : undefined); } @@ -45028,6 +45088,9 @@ var ts; } return toSearchResult(/*value*/ undefined); } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); + } var finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); var inputLink = tryLoadInputFileForPath(finalPath, subpath, ts.combinePaths(scope.packageDirectory, "package.json"), isImports); if (inputLink) @@ -45037,14 +45100,18 @@ var ts; else if (typeof target === "object" && target !== null) { // eslint-disable-line no-null/no-null if (!Array.isArray(target)) { for (var _i = 0, _a = ts.getOwnKeys(target); _i < _a.length; _i++) { - var key = _a[_i]; - if (key === "default" || state.conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(state.conditions, key)) { - var subTarget = target[key]; - var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern); + var condition = _a[_i]; + if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) { + traceIfEnabled(state, ts.Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition); + var subTarget = target[condition]; + var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key); if (result) { return result; } } + else { + traceIfEnabled(state, ts.Diagnostics.Saw_non_matching_condition_0, condition); + } } return undefined; } @@ -45057,7 +45124,7 @@ var ts; } for (var _b = 0, target_2 = target; _b < target_2.length; _b++) { var elem = target_2[_b]; - var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern); + var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern, key); if (result) { return result; } @@ -45473,6 +45540,15 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } + function traceIfEnabled(state, diagnostic) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (state.traceEnabled) { + trace.apply(void 0, __spreadArray([state.host, diagnostic], args, false)); + } + } })(ts || (ts = {})); /* @internal */ var ts; @@ -49064,8 +49140,6 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; - IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var RecursionFlags; (function (RecursionFlags) { @@ -49484,6 +49558,12 @@ var ts; getOptionalType: function () { return optionalType; }, getPromiseType: function () { return getGlobalPromiseType(/*reportErrors*/ false); }, getPromiseLikeType: function () { return getGlobalPromiseLikeType(/*reportErrors*/ false); }, + getAsyncIterableType: function () { + var type = getGlobalAsyncIterableType(/*reportErrors*/ false); + if (type === emptyGenericType) + return undefined; + return type; + }, isSymbolAccessible: isSymbolAccessible, isArrayType: isArrayType, isTupleType: isTupleType, @@ -50321,9 +50401,9 @@ var ts; return symbol; } if (symbol.flags & 2097152 /* SymbolFlags.Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { + var targetFlags = getAllSymbolFlags(symbol); + // `targetFlags` will be `SymbolFlags.All` if an error occurred in alias resolution; this avoids cascading errors + if (targetFlags & meaning) { return symbol; } } @@ -50956,8 +51036,8 @@ var ts; !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && + !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; var suggestedLib = void 0; @@ -51044,7 +51124,7 @@ var ts; } } if (result && errorLocation && meaning & 111551 /* SymbolFlags.Value */ && result.flags & 2097152 /* SymbolFlags.Alias */ && !(result.flags & 111551 /* SymbolFlags.Value */) && !ts.isValidTypeOnlyAliasUseSite(errorLocation)) { - var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); + var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551 /* SymbolFlags.Value */); if (typeOnlyDeclaration) { var message = typeOnlyDeclaration.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type @@ -51207,7 +51287,7 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { + if (meaning & 111551 /* SymbolFlags.Value */) { if (isPrimitiveTypeName(name)) { if (isExtendedByInterface(errorLocation)) { error(errorLocation, ts.Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, ts.unescapeLeadingUnderscores(name)); @@ -51218,7 +51298,8 @@ var ts; return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); - if (symbol && !(symbol.flags & 1024 /* SymbolFlags.NamespaceModule */)) { + var allFlags = symbol && getAllSymbolFlags(symbol); + if (symbol && allFlags !== undefined && !(allFlags & 111551 /* SymbolFlags.Value */)) { var rawName = ts.unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName); @@ -51266,16 +51347,16 @@ var ts; } return false; } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~788968 /* SymbolFlags.Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) { + if (meaning & (111551 /* SymbolFlags.Value */ & ~788968 /* SymbolFlags.Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (788968 /* SymbolFlags.Type */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* SymbolFlags.ValueModule */ | 1024 /* SymbolFlags.NamespaceModule */) & ~788968 /* SymbolFlags.Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1536 /* SymbolFlags.Module */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -51865,6 +51946,52 @@ var ts; } return undefined; } + /** + * Gets combined flags of a `symbol` and all alias targets it resolves to. `resolveAlias` + * is typically recursive over chains of aliases, but stops mid-chain if an alias is merged + * with another exported symbol, e.g. + * ```ts + * // a.ts + * export const a = 0; + * // b.ts + * export { a } from "./a"; + * export type a = number; + * // c.ts + * import { a } from "./b"; + * ``` + * Calling `resolveAlias` on the `a` in c.ts would stop at the merged symbol exported + * from b.ts, even though there is still more alias to resolve. Consequently, if we were + * trying to determine if the `a` in c.ts has a value meaning, looking at the flags on + * the local symbol and on the symbol returned by `resolveAlias` is not enough. + * @returns SymbolFlags.All if `symbol` is an alias that ultimately resolves to `unknown`; + * combined flags of all alias targets otherwise. + */ + function getAllSymbolFlags(symbol) { + var flags = symbol.flags; + var seenSymbols; + while (symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return 67108863 /* SymbolFlags.All */; + } + // Optimizations - try to avoid creating or adding to + // `seenSymbols` if possible + if (target === symbol || (seenSymbols === null || seenSymbols === void 0 ? void 0 : seenSymbols.has(target))) { + break; + } + if (target.flags & 2097152 /* SymbolFlags.Alias */) { + if (seenSymbols) { + seenSymbols.add(target); + } + else { + seenSymbols = new ts.Set([symbol, target]); + } + } + flags |= target.flags; + symbol = target; + } + return flags; + } /** * Marks a symbol as type-only if its declaration is syntactically type-only. * If it is not itself marked type-only, but resolves to a type-only alias @@ -51910,19 +52037,25 @@ var ts; return !!aliasDeclarationLinks.typeOnlyDeclaration; } /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */ - function getTypeOnlyAliasDeclaration(symbol) { + function getTypeOnlyAliasDeclaration(symbol, include) { if (!(symbol.flags & 2097152 /* SymbolFlags.Alias */)) { return undefined; } var links = getSymbolLinks(symbol); - return links.typeOnlyDeclaration || undefined; + if (include === undefined) { + return links.typeOnlyDeclaration || undefined; + } + if (links.typeOnlyDeclaration) { + return getAllSymbolFlags(resolveAlias(links.typeOnlyDeclaration.symbol)) & include ? links.typeOnlyDeclaration : undefined; + } + return undefined; } function markExportAsReferenced(node) { var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol)); + ((getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -51942,8 +52075,7 @@ var ts; // This way a chain of imports can be elided if ultimately the final input is only used in a type // position. if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveSymbol(symbol); - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* SymbolFlags.Value */) { // import foo = checkExpressionCached(node.moduleReference); } @@ -52765,7 +52897,7 @@ var ts; } function symbolIsValue(symbol, includeTypeOnlyMembers) { return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || - symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + symbol.flags & 2097152 /* SymbolFlags.Alias */ && getAllSymbolFlags(symbol) & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -53034,8 +53166,10 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { + var shouldResolveAlias = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)); + symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + var flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + if (flags & meaning) { qualify = true; return true; } @@ -55347,7 +55481,7 @@ var ts; // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it var indices = ts.indicesOf(statements); var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); }); - if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) { + if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return ts.canHaveExportModifier(statements[i]); })) { for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) { var index_1 = associatedIndices_1[_i]; statements[index_1] = addExportModifier(statements[index_1]); @@ -55381,15 +55515,6 @@ var ts; } return statements; } - function canHaveExportModifier(node) { - return ts.isEnumDeclaration(node) || - ts.isVariableStatement(node) || - ts.isFunctionDeclaration(node) || - ts.isClassDeclaration(node) || - (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) || - ts.isInterfaceDeclaration(node) || - isTypeDeclaration(node); - } function addExportModifier(node) { var flags = (ts.getEffectiveModifierFlags(node) | 1 /* ModifierFlags.Export */) & ~2 /* ModifierFlags.Ambient */; return ts.factory.updateModifiers(node, flags); @@ -55636,7 +55761,7 @@ var ts; (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* ModifierFlags.Export */ && enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && - canHaveExportModifier(node)) { + ts.canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* ModifierFlags.Export */; } @@ -55692,7 +55817,7 @@ var ts; return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { - return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* SymbolFlags.Value */); }); + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* SymbolFlags.Value */); }); } function serializeModule(symbol, symbolName, modifierFlags) { var members = getNamespaceMembersForSerialization(symbol); @@ -57912,7 +58037,7 @@ var ts; links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType - : targetSymbol.flags & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) + : getAllSymbolFlags(targetSymbol) & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; @@ -59795,7 +59920,20 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ && getMappedTypeModifiers(type) & 4 /* MappedTypeModifiers.IncludeOptional */); } function isGenericMappedType(type) { - return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + if (ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) { + var constraint = getConstraintTypeFromMappedType(type); + if (isGenericIndexType(constraint)) { + return true; + } + // A mapped type is generic if the 'as' clause references generic types other than the iteration type. + // To determine this, we substitute the constraint type (that we now know isn't generic) for the iteration + // type and check whether the resulting type is generic. + var nameType = getNameTypeFromMappedType(type); + if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) { + return true; + } + } + return false; } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -60265,7 +60403,7 @@ var ts; var indexTypes; var isUnion = containingType.flags & 1048576 /* TypeFlags.Union */; // Flags we want to propagate to the result if they exist in all source symbols - var optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */; + var optionalFlag; var syntheticFlag = 4 /* CheckFlags.SyntheticMethod */; var checkFlags = isUnion ? 0 : 8 /* CheckFlags.Readonly */; var mergedInstantiations = false; @@ -60276,11 +60414,14 @@ var ts; var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop) { - if (isUnion) { - optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); - } - else { - optionalFlag &= prop.flags; + if (prop.flags & 106500 /* SymbolFlags.ClassMember */) { + optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : (optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */); + if (isUnion) { + optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); + } + else { + optionalFlag &= prop.flags; + } } if (!singleProp) { singleProp = prop; @@ -60399,7 +60540,7 @@ var ts; propTypes.push(type); } ts.addRange(propTypes, indexTypes); - var result = createSymbol(4 /* SymbolFlags.Property */ | optionalFlag, name, syntheticFlag | checkFlags); + var result = createSymbol(4 /* SymbolFlags.Property */ | (optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : 0), name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && firstValueDeclaration) { result.valueDeclaration = firstValueDeclaration; @@ -63112,8 +63253,14 @@ var ts; return getStringLiteralType(text); } newTexts.push(text); - if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { - return stringType; + if (ts.every(newTexts, function (t) { return t === ""; })) { + if (ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { + return stringType; + } + // Normalize `${Mapping}` into Mapping + if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) { + return newTypes[0]; + } } var id = "".concat(getTypeListId(newTypes), "|").concat(ts.map(newTexts, function (t) { return t.length; }).join(","), "|").concat(newTexts.join("")); var type = templateLiteralTypes.get(id); @@ -63172,12 +63319,14 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - // Mapping> === Mapping - type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : - isGenericIndexType(type) || isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, isPatternLiteralPlaceholderType(type) && !(type.flags & 268435456 /* TypeFlags.StringMapping */) ? getTemplateLiteralType(["", ""], [type]) : type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : - type; + type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : + type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : + // Mapping> === Mapping + type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : + type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : + // This handles Mapping<`${number}`> and Mapping<`${bigint}`> + isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : + type; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -63342,7 +63491,18 @@ var ts; return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; } errorIfWritingToReadonlyIndex(indexInfo); - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; + // When accessing an enum object with its own type, + // e.g. E[E.A] for enum E { A }, undefined shouldn't + // be included in the result type + if ((accessFlags & 1 /* AccessFlags.IncludeUndefined */) && + !(objectType.symbol && + objectType.symbol.flags & (256 /* SymbolFlags.RegularEnum */ | 128 /* SymbolFlags.ConstEnum */) && + (indexType.symbol && + indexType.flags & 1024 /* TypeFlags.EnumLiteral */ && + getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + return getUnionType([indexInfo.type, undefinedType]); + } + return indexInfo.type; } if (indexType.flags & 131072 /* TypeFlags.Never */) { return neverType; @@ -63445,10 +63605,11 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || isPatternLiteralType(type); } function isPatternLiteralType(type) { - return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); + return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType) || + !!(type.flags & 268435456 /* TypeFlags.StringMapping */) && isPatternLiteralPlaceholderType(type.type); } function isGenericType(type) { return !!getGenericObjectFlags(type); @@ -63727,18 +63888,23 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_20 = function () { + // We loop here for an immediately nested conditional type in the false position, effectively treating + // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for + // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of + // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive + // cases we increment the tail recursion counter and stop after 1000 iterations. + while (true) { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; - return "break"; + break; } var isUnwrapped = isTypicalNondistributiveConditional(root); var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { - return { value: wildcardType }; + return wildcardType; } var combinedMapper = void 0; if (root.inferTypeParameters) { @@ -63771,11 +63937,7 @@ var ts; } } } - // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type - // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to - // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint - // so in those cases we refain from performing inference and retain the uninfered type parameter - if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -63807,14 +63969,14 @@ var ts; var newRoot = falseType_1.root; if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) { root = newRoot; - return "continue"; + continue; } if (canTailRecurse(falseType_1, mapper)) { - return "continue"; + continue; } } result = instantiateType(falseType_1, mapper); - return "break"; + break; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -63825,10 +63987,10 @@ var ts; var trueType_1 = getTypeFromTypeNode(root.node.trueType); var trueMapper = combinedMapper || mapper; if (canTailRecurse(trueType_1, trueMapper)) { - return "continue"; + continue; } result = instantiateType(trueType_1, trueMapper); - return "break"; + break; } } // Return a deferred type for a check that is neither definitely true nor definitely false @@ -63840,19 +64002,7 @@ var ts; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 - return "break"; - }; - // We loop here for an immediately nested conditional type in the false position, effectively treating - // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for - // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of - // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive - // cases we increment the tail recursion counter and stop after 1000 iterations. - while (true) { - var state_6 = _loop_20(); - if (typeof state_6 === "object") - return state_6.value; - if (state_6 === "break") - break; + break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; // We tail-recurse for generic conditional types that (a) have not already been evaluated and cached, and @@ -66306,7 +66456,7 @@ var ts; return 0 /* Ternary.False */; } } - var isPerformingCommonPropertyChecks = (relation !== comparableRelation || !(source.flags & 1048576 /* TypeFlags.Union */) && isLiteralType(source)) && + var isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source)) && !(intersectionState & 2 /* IntersectionState.Target */) && source.flags & (131068 /* TypeFlags.Primitive */ | 524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && source !== globalObjectType && target.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && isWeakType(target) && @@ -66334,27 +66484,6 @@ var ts; var result_7 = skipCaching ? unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) : recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags); - // For certain combinations involving intersections and optional, excess, or mismatched properties we need - // an extra property check where the intersection is viewed as a single object. The following are motivating - // examples that all should be errors, but aren't without this extra property check: - // - // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property - // - // declare let wrong: { a: { y: string } }; - // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type - // - // function foo(x: { a?: string }, y: T & { a: boolean }) { - // x = y; // Mismatched property in source intersection - // } - // - // We suppress recursive intersection property checks because they can generate lots of work when relating - // recursive intersections that are structurally similar but not exactly identical. See #37854. - if (result_7 && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { - inPropertyCheck = true; - result_7 &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* IntersectionState.PropertyCheck */, recursionFlags); - inPropertyCheck = false; - } if (result_7) { return result_7; } @@ -66466,7 +66595,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_21 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -66529,9 +66658,9 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_7 = _loop_21(prop); - if (typeof state_7 === "object") - return state_7.value; + var state_6 = _loop_20(prop); + if (typeof state_6 === "object") + return state_6.value; } return false; } @@ -66752,8 +66881,7 @@ var ts; if (overflow) { return 0 /* Ternary.False */; } - var keyIntersectionState = intersectionState | (inPropertyCheck ? 8 /* IntersectionState.InPropertyCheck */ : 0); - var id = getRelationKey(source, target, keyIntersectionState, relation, /*ingnoreConstraints*/ false); + var id = getRelationKey(source, target, intersectionState, relation, /*ingnoreConstraints*/ false); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* RelationComparisonResult.Failed */ && !(entry & 4 /* RelationComparisonResult.Reported */)) { @@ -66783,7 +66911,7 @@ var ts; // A key that starts with "*" is an indication that we have type references that reference constrained // type parameters. For such keys we also check against the key we would have gotten if all type parameters // were unconstrained. - var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, keyIntersectionState, relation, /*ignoreConstraints*/ true) : undefined; + var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, intersectionState, relation, /*ignoreConstraints*/ true) : undefined; for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { @@ -66870,7 +66998,7 @@ var ts; function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { var saveErrorInfo = captureErrorCalculationState(); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo); - if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + if (relation !== identityRelation) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -66884,10 +67012,33 @@ var ts; // needs to have its constraint hoisted into an intersection with said type parameter, this way // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` - var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); - if (constraint && !(constraint.flags & 131072 /* TypeFlags.Never */) && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself - // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this - result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); + if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself + // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this + result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + } + } + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && !isGenericObjectType(target) && source.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) || + isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { + inPropertyCheck = true; + result &= propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); + inPropertyCheck = false; } } if (result) { @@ -66896,9 +67047,6 @@ var ts; return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo) { - if (intersectionState & 4 /* IntersectionState.PropertyCheck */) { - return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); - } var result; var originalErrorInfo; var varianceCheckFailed = false; @@ -66999,7 +67147,7 @@ var ts; // with another type parameter unless one extends the other. (Remember: comparability is mostly bidirectional!) var constraint = getConstraintOfTypeParameter(source); if (constraint && hasNonCircularBaseConstraint(source)) { - while (constraint && constraint.flags & 262144 /* TypeFlags.TypeParameter */) { + while (constraint && someType(constraint, function (c) { return !!(c.flags & 262144 /* TypeFlags.TypeParameter */); })) { if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { return result; } @@ -67522,11 +67670,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_22 = function (combination) { + var _loop_21 = function (combination) { var hasMatch = false; outer: for (var _c = 0, _d = target.types; _c < _d.length; _c++) { var type = _d[_c]; - var _loop_23 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -67542,8 +67690,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_9 = _loop_23(i); - switch (state_9) { + var state_8 = _loop_22(i); + switch (state_8) { case "continue-outer": continue outer; } } @@ -67556,9 +67704,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_8 = _loop_22(combination); - if (typeof state_8 === "object") - return state_8.value; + var state_7 = _loop_21(combination); + if (typeof state_7 === "object") + return state_7.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* Ternary.True */; @@ -67655,7 +67803,7 @@ var ts; return 0 /* Ternary.False */; } // When checking for comparability, be more lenient with optional properties. - if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && targetProp.flags & 106500 /* SymbolFlags.ClassMember */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -68263,7 +68411,7 @@ var ts; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); links.variances = ts.emptyArray; var variances = []; - var _loop_24 = function (tp) { + var _loop_23 = function (tp) { var modifiers = getVarianceModifiers(tp); var variance = modifiers & 65536 /* ModifierFlags.Out */ ? modifiers & 32768 /* ModifierFlags.In */ ? 0 /* VarianceFlags.Invariant */ : 1 /* VarianceFlags.Covariant */ : @@ -68301,7 +68449,7 @@ var ts; }; for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var tp = typeParameters_2[_i]; - _loop_24(tp); + _loop_23(tp); } links.variances = variances; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); @@ -68755,8 +68903,7 @@ var ts; return !!(type.flags & 109440 /* TypeFlags.Unit */); } function isUnitLikeType(type) { - return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.some(type.types, isUnitType) : - !!(type.flags & 109440 /* TypeFlags.Unit */); + return isUnitType(getBaseConstraintOrType(type)); } function extractUnitType(type) { return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.find(type.types, isUnitType) || type : type; @@ -69635,7 +69782,7 @@ var ts; && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); } function isMemberOfStringMapping(source, target) { - if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + if (target.flags & (4 /* TypeFlags.String */ | 1 /* TypeFlags.Any */)) { return true; } if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { @@ -70259,7 +70406,7 @@ var ts; // upon instantiation, would collapse all the placeholders to just 'string', and an assignment check might // succeed. That would be a pointless and confusing outcome. if (matches || ts.every(target.texts, function (s) { return s.length === 0; })) { - var _loop_25 = function (i) { + var _loop_24 = function (i) { var source_1 = matches ? matches[i] : neverType; var target_3 = types[i]; // If we are inferring from a string literal type to a type variable whose constraint includes one of the @@ -70309,7 +70456,7 @@ var ts; inferFromTypes(source_1, target_3); }; for (var i = 0; i < types.length; i++) { - _loop_25(i); + _loop_24(i); } } } @@ -70761,7 +70908,7 @@ var ts; } if (ts.isEntityNameExpression(node.argumentExpression)) { var symbol = resolveEntityName(node.argumentExpression, 111551 /* SymbolFlags.Value */, /*ignoreErrors*/ true); - if (!symbol || !isConstVariable(symbol)) + if (!symbol || !(isConstVariable(symbol) || (symbol.flags & 8 /* SymbolFlags.EnumMember */))) return undefined; var declaration = symbol.valueDeclaration; if (declaration === undefined) @@ -70775,7 +70922,12 @@ var ts; } if (ts.hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node.argumentExpression)) { var initializer = ts.getEffectiveInitializer(declaration); - return initializer && tryGetNameFromType(getTypeOfExpression(initializer)); + if (initializer) { + return tryGetNameFromType(getTypeOfExpression(initializer)); + } + if (ts.isEnumMember(declaration)) { + return ts.getTextOfPropertyName(declaration.name); + } } } return undefined; @@ -70833,7 +70985,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_26 = function (type) { + var _loop_25 = function (type) { if (type.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */ | 58982400 /* TypeFlags.InstantiableNonPrimitive */)) { var discriminant = getTypeOfPropertyOfType(type, name); if (discriminant) { @@ -70859,9 +71011,9 @@ var ts; }; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var type = types_15[_i]; - var state_10 = _loop_26(type); - if (typeof state_10 === "object") - return state_10.value; + var state_9 = _loop_25(type); + if (typeof state_9 === "object") + return state_9.value; } return count >= 10 && count * 2 >= types.length ? map : undefined; } @@ -71458,6 +71610,7 @@ var ts; ts.isInJSFile(node) && ts.hasInitializer(node) && node.initializer && ts.isFunctionExpressionOrArrowFunction(node.initializer) && ts.getEffectiveReturnTypeNode(node.initializer)); } function getExplicitTypeOfSymbol(symbol, diagnostic) { + symbol = resolveSymbol(symbol); if (symbol.flags & (16 /* SymbolFlags.Function */ | 8192 /* SymbolFlags.Method */ | 32 /* SymbolFlags.Class */ | 512 /* SymbolFlags.ValueModule */)) { return getTypeOfSymbol(symbol); } @@ -71496,7 +71649,7 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); - return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol, diagnostic); + return getExplicitTypeOfSymbol(symbol, diagnostic); case 108 /* SyntaxKind.ThisKeyword */: return getExplicitThisType(node); case 106 /* SyntaxKind.SuperKeyword */: @@ -71983,7 +72136,7 @@ var ts; type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (expr.kind === 218 /* SyntaxKind.TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { - type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { if (strictNullChecks) { @@ -72264,7 +72417,7 @@ var ts; !!(prop.flags & 16777216 /* SymbolFlags.Optional */) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue; } - function narrowByInKeyword(type, nameType, assumeTrue) { + function narrowTypeByInKeyword(type, nameType, assumeTrue) { var name = getPropertyNameFromType(nameType); var isKnownProperty = someType(type, function (t) { return isTypePresencePossible(t, name, /*assumeTrue*/ true); }); if (isKnownProperty) { @@ -72345,7 +72498,7 @@ var ts; return getTypeWithFacts(type, assumeTrue ? 524288 /* TypeFacts.NEUndefined */ : 65536 /* TypeFacts.EQUndefined */); } if (isMatchingReference(reference, target)) { - return narrowByInKeyword(type, leftType, assumeTrue); + return narrowTypeByInKeyword(type, leftType, assumeTrue); } } break; @@ -72534,7 +72687,7 @@ var ts; neverType; }); } - function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + function narrowTypeBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!witnesses) { return type; @@ -72922,15 +73075,15 @@ var ts; }); } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { var target = resolveAlias(symbol); - if (target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */)) { // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled // (because the const enum value will not be inlined), or if (2) the alias is an export // of a const enum declaration that will be preserved. if (compilerOptions.isolatedModules || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || - !isConstEnumOrConstEnumOnlyModule(target)) { + !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -73158,7 +73311,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 16384 /* TypeFlags.Void */)) !== 0 || isInTypeQuery(node) || node.parent.kind === 278 /* SyntaxKind.ExportSpecifier */) || node.parent.kind === 232 /* SyntaxKind.NonNullExpression */ || @@ -73187,6 +73340,12 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function isSameScopedBindingElement(node, declaration) { + if (ts.isBindingElement(declaration)) { + var bindingElement = ts.findAncestor(node, ts.isBindingElement); + return bindingElement && ts.getRootDeclaration(bindingElement) === ts.getRootDeclaration(declaration); + } + } function shouldMarkIdentifierAliasReferenced(node) { var _a; var parent = node.parent; @@ -73528,12 +73687,17 @@ var ts; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; + var inAsyncFunction = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { while (container && container.kind === 216 /* SyntaxKind.ArrowFunction */) { + if (ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ScriptTarget.ES2015 */; } + if (container && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; @@ -73639,12 +73803,12 @@ var ts; // as a call expression cannot be used as the target of a destructuring assignment while a property access can. // // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. - if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) { + if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && inAsyncFunction) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */; + getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */; } else { - getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.AsyncMethodWithSuper */; + getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */; } } if (needToCaptureLexicalThis) { @@ -74340,9 +74504,10 @@ var ts; function instantiateContextualType(contextualType, node, contextFlags) { if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* TypeFlags.Instantiable */)) { var inferenceContext = getInferenceContext(node); - // If no inferences have been made, nothing is gained from instantiating as type parameters - // would just be replaced with their defaults similar to the apparent type. - if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + // If no inferences have been made, and none of the type parameters for which we are inferring + // specify default types, nothing is gained from instantiating as type parameters would just be + // replaced with their constraints similar to the apparent type. + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) { // For contextual signatures we incorporate all inferences made so far, e.g. from return // types as well as arguments to the left in a function call. return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); @@ -77316,7 +77481,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_27 = function (i) { + var _loop_26 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. var spreadType = arg.kind === 227 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -77333,7 +77498,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_27(i); + _loop_26(i); } return effectiveArgs_1; } @@ -77662,7 +77827,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_28 = function (c) { + var _loop_27 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* CheckMode.Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -77680,7 +77845,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_28(c); + _loop_27(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -77838,7 +78003,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_29 = function (i) { + var _loop_28 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -77846,7 +78011,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_29(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -78816,7 +78981,7 @@ var ts; if (symbol && symbol.flags & 2097152 /* SymbolFlags.Alias */) { symbol = resolveAlias(symbol); } - return !!(symbol && (symbol.flags & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); + return !!(symbol && (getAllSymbolFlags(symbol) & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); } return false; } @@ -79478,7 +79643,17 @@ var ts; } function isExhaustiveSwitchStatement(node) { var links = getNodeLinks(node); - return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); + if (links.isExhaustive === undefined) { + links.isExhaustive = 0; // Indicate resolution is in process + var exhaustive = computeExhaustiveSwitchStatement(node); + if (links.isExhaustive === 0) { + links.isExhaustive = exhaustive; + } + } + else if (links.isExhaustive === 0) { + links.isExhaustive = false; // Resolve circularity to false + } + return links.isExhaustive; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 218 /* SyntaxKind.TypeOfExpression */) { @@ -79486,7 +79661,7 @@ var ts; if (!witnesses) { return false; } - var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(node.expression.expression)); + var operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression)); // Get the not-equal flags for all handled cases. var notEqualFacts_2 = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); if (operandConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */) { @@ -79496,7 +79671,7 @@ var ts; // A missing not-equal flag indicates that the type wasn't handled by some case. return !someType(operandConstraint, function (t) { return (getTypeFacts(t) & notEqualFacts_2) === notEqualFacts_2; }); } - var type = getTypeOfExpression(node.expression); + var type = checkExpressionCached(node.expression); if (!isLiteralType(type)) { return false; } @@ -81190,6 +81365,9 @@ var ts; function hasInferenceCandidates(info) { return !!(info.candidates || info.contraCandidates); } + function hasInferenceCandidatesOrDefault(info) { + return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter)); + } function hasOverlappingInferences(a, b) { for (var i = 0; i < a.length; i++) { if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) { @@ -81891,7 +82069,7 @@ var ts; var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var indexSignatureMap_1 = new ts.Map(); - var _loop_30 = function (declaration) { + var _loop_29 = function (declaration) { if (declaration.parameters.length === 1 && declaration.parameters[0].type) { forEachType(getTypeFromTypeNode(declaration.parameters[0].type), function (type) { var entry = indexSignatureMap_1.get(getTypeId(type)); @@ -81906,7 +82084,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_30(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -82183,7 +82361,7 @@ var ts; } var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { - if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { + if (ts.some(symbol.declarations, function (d) { return ts.isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* TypeFlags.Enum */ && symbol.flags & 8 /* SymbolFlags.EnumMember */) { @@ -82786,7 +82964,7 @@ var ts; return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; } // primitives with a `{ then() }` won't be unwrapped/adopted. - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217 @@ -82853,7 +83031,7 @@ var ts; * Determines whether a type is an object with a callable `then` member. */ function isThenableType(type) { - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { // primitive types cannot be considered "thenable" since they are not objects. return false; } @@ -82887,7 +83065,7 @@ var ts; // We only need `Awaited` if `T` is a type variable that has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`, // or is promise-like. if (baseConstraint ? - baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint) : + baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { return true; } @@ -83561,7 +83739,7 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + var message = ts.isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(declaration, 0 /* UnusedKind.Local */, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { @@ -84991,7 +85169,16 @@ var ts; var message = allowAsyncIterables ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; - return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + var suggestAwait = + // for (const x of Promise<...>) or [...Promise<...>] + !!getAwaitedTypeOfPromise(type) + // for (const x of AsyncIterable<...>) + || (!allowAsyncIterables && + ts.isForOfStatement(errorNode.parent) && + errorNode.parent.expression === errorNode && + getGlobalAsyncIterableType(/** reportErrors */ false) !== emptyGenericType && + isTypeAssignableTo(type, getGlobalAsyncIterableType(/** reportErrors */ false))); + return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. @@ -85506,7 +85693,7 @@ var ts; var propDeclaration = declaration && declaration.kind === 223 /* SyntaxKind.BinaryExpression */ || name && name.kind === 164 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_31 = function (info) { + var _loop_30 = function (info) { var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; // We check only when (a) the property is declared in the containing type, or (b) the applicable index signature is declared // in the containing type, or (c) the containing type is an interface and no base interface contains both the property and @@ -85523,7 +85710,7 @@ var ts; }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_31(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -85531,7 +85718,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 261 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_32 = function (info) { + var _loop_31 = function (info) { if (info === checkInfo) return "continue"; var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; @@ -85546,7 +85733,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_32(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -85601,7 +85788,7 @@ var ts; } else { ts.forEach(jsdocParameters, function (_a, index) { - var name = _a.name; + var name = _a.name, isNameFirst = _a.isNameFirst; if (excludedParameters.has(index) || ts.isIdentifier(name) && parameters.has(name.escapedText)) { return; } @@ -85611,7 +85798,9 @@ var ts; } } else { - errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + if (!isNameFirst) { + errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + } } }); } @@ -85866,7 +86055,7 @@ var ts; 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 _loop_33 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -85883,7 +86072,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_33(member); + _loop_32(member); } } /** @@ -85971,7 +86160,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_34 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -85990,7 +86179,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_34(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -86061,7 +86250,7 @@ var ts; var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - var _loop_35 = function (baseProperty) { + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { return "continue"; @@ -86171,8 +86360,8 @@ var ts; }; basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { var baseProperty = baseProperties_1[_i]; - var state_11 = _loop_35(baseProperty); - switch (state_11) { + var state_10 = _loop_34(baseProperty); + switch (state_10) { case "continue-basePropertyCheck": continue basePropertyCheck; } } @@ -86691,12 +86880,11 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { - var _a; switch (node.kind) { case 240 /* SyntaxKind.VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { - var decl = _b[_i]; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; @@ -86712,8 +86900,8 @@ var ts; case 257 /* SyntaxKind.VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { - var el = _d[_c]; + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -86729,18 +86917,6 @@ var ts; if (isGlobalAugmentation) { return; } - var symbol = getSymbolOfNode(node); - if (symbol) { - // module augmentations cannot introduce new names on the top level scope of the module - // this is done it two steps - // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error - // 2. main check - report error if value declaration of the parent symbol is module augmentation) - var reportError = !(symbol.flags & 33554432 /* SymbolFlags.Transient */); - if (!reportError) { - // symbol should not originate in augmentation - reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } break; } } @@ -86842,10 +87018,11 @@ var ts; } return; } + var targetFlags = getAllSymbolFlags(target); var excludedMeanings = (symbol.flags & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */) ? 111551 /* SymbolFlags.Value */ : 0) | (symbol.flags & 788968 /* SymbolFlags.Type */ ? 788968 /* SymbolFlags.Type */ : 0) | (symbol.flags & 1920 /* SymbolFlags.Namespace */ ? 1920 /* SymbolFlags.Namespace */ : 0); - if (target.flags & excludedMeanings) { + if (targetFlags & excludedMeanings) { var message = node.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; @@ -86855,7 +87032,7 @@ var ts; && !ts.isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 16777216 /* NodeFlags.Ambient */)) { var typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol); - var isType = !(target.flags & 111551 /* SymbolFlags.Value */); + var isType = !(targetFlags & 111551 /* SymbolFlags.Value */); if (isType || typeOnlyAlias) { switch (node.kind) { case 270 /* SyntaxKind.ImportClause */: @@ -87015,14 +87192,15 @@ var ts; if (node.moduleReference.kind !== 280 /* SyntaxKind.ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 111551 /* SymbolFlags.Value */) { + var targetFlags = getAllSymbolFlags(target); + if (targetFlags & 111551 /* SymbolFlags.Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* SymbolFlags.Value */ | 1920 /* SymbolFlags.Namespace */).flags & 1920 /* SymbolFlags.Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 788968 /* SymbolFlags.Type */) { + if (targetFlags & 788968 /* SymbolFlags.Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -87161,7 +87339,7 @@ var ts; markExportAsReferenced(node); } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); - if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (!target || getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); } } @@ -87208,7 +87386,7 @@ var ts; markAliasReferenced(sym, id); // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`) var target = sym.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(sym) : sym; - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { // However if it is a value, we need to check it's being used correctly checkExpressionCached(node.expression); } @@ -87880,29 +88058,9 @@ var ts; } function isTypeDeclarationName(name) { return name.kind === 79 /* SyntaxKind.Identifier */ && - isTypeDeclaration(name.parent) && + ts.isTypeDeclaration(name.parent) && ts.getNameOfDeclaration(name.parent) === name; } - function isTypeDeclaration(node) { - switch (node.kind) { - case 165 /* SyntaxKind.TypeParameter */: - case 260 /* SyntaxKind.ClassDeclaration */: - case 261 /* SyntaxKind.InterfaceDeclaration */: - case 262 /* SyntaxKind.TypeAliasDeclaration */: - case 263 /* SyntaxKind.EnumDeclaration */: - case 348 /* SyntaxKind.JSDocTypedefTag */: - case 341 /* SyntaxKind.JSDocCallbackTag */: - case 342 /* SyntaxKind.JSDocEnumTag */: - return true; - case 270 /* SyntaxKind.ImportClause */: - return node.isTypeOnly; - case 273 /* SyntaxKind.ImportSpecifier */: - case 278 /* SyntaxKind.ExportSpecifier */: - return node.parent.parent.isTypeOnly; - default: - return false; - } - } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { while (node.parent.kind === 163 /* SyntaxKind.QualifiedName */) { @@ -88335,7 +88493,7 @@ var ts; var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } - if (isTypeDeclaration(node)) { + if (ts.isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration var symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); @@ -88530,7 +88688,7 @@ var ts; return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 111551 /* SymbolFlags.Value */); + return s && !!(getAllSymbolFlags(s) & 111551 /* SymbolFlags.Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -88583,7 +88741,7 @@ var ts; var symbol = getReferencedValueOrAliasSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -88671,7 +88829,7 @@ var ts; case 273 /* SyntaxKind.ImportSpecifier */: case 278 /* SyntaxKind.ExportSpecifier */: var symbol = getSymbolOfNode(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); + return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */); case 275 /* SyntaxKind.ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || @@ -88693,6 +88851,7 @@ var ts; return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); } function isAliasResolvedToValue(symbol) { + var _a; if (!symbol) { return false; } @@ -88702,7 +88861,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 111551 /* SymbolFlags.Value */) && + return !!(((_a = getAllSymbolFlags(target)) !== null && _a !== void 0 ? _a : -1) & 111551 /* SymbolFlags.Value */) && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -88717,7 +88876,7 @@ var ts; } var target = getSymbolLinks(symbol).aliasTarget; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* ModifierFlags.Export */ && - target.flags & 111551 /* SymbolFlags.Value */ && + getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */ && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; @@ -98371,8 +98530,11 @@ var ts; } return ts.visitEachChild(node, visitor, context); case 174 /* SyntaxKind.GetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitGetAccessorDeclaration, node); case 175 /* SyntaxKind.SetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitSetAccessorDeclaration, node); case 173 /* SyntaxKind.Constructor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitConstructorDeclaration, node); case 260 /* SyntaxKind.ClassDeclaration */: case 228 /* SyntaxKind.ClassExpression */: return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitDefault, node); @@ -98473,6 +98635,9 @@ var ts; return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression( /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); + } /** * Visits a MethodDeclaration node. * @@ -98487,7 +98652,14 @@ var ts; /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) - : ts.visitFunctionBody(node.body, visitor, context)); + : transformMethodBody(node)); + } + function visitGetAccessorDeclaration(node) { + return factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformMethodBody(node)); + } + function visitSetAccessorDeclaration(node) { + return factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); } /** * Visits a FunctionDeclaration node. @@ -98601,6 +98773,42 @@ var ts; } return false; } + function transformMethodBody(node) { + ts.Debug.assertIsDefined(node.body); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = new ts.Set(); + hasSuperElementAccess = false; + var updated = ts.visitFunctionBody(node.body, visitor, context); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var originalMethod = ts.getOriginalNode(node, ts.isFunctionLikeDeclaration); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && + resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) && + (ts.getFunctionFlags(originalMethod) & 3 /* FunctionFlags.AsyncGenerator */) !== 3 /* FunctionFlags.AsyncGenerator */; + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + if (capturedSuperProperties.size) { + var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + var statements = updated.statements.slice(); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + updated = factory.updateBlock(updated, statements); + } + if (hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { + ts.addEmitHelper(updated, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { + ts.addEmitHelper(updated, ts.asyncSuperHelper); + } + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return updated; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -98633,7 +98841,7 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { @@ -98646,10 +98854,10 @@ var ts; ts.setTextRange(block, node.body); if (emitSuperHelpers && hasSuperElementAccess) { // Emit helpers for super element access expressions (`super[x]`). - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -98721,7 +98929,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ES2017SubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -98798,7 +99006,7 @@ var ts; || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -98813,7 +99021,7 @@ var ts; function createSuperAccessVariableStatement(factory, resolver, node, names) { // Create a variable declaration with a getter/setter (if binding) definition for each name: // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); - var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) !== 0; + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) !== 0; var accessors = []; names.forEach(function (_, key) { var name = ts.unescapeLeadingUnderscores(key); @@ -99306,11 +99514,22 @@ var ts; } return node; } - function convertForOfStatementHead(node, boundValue) { - var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue); + function convertForOfStatementHead(node, boundValue, nonUserCode) { + var value = factory.createTempVariable(hoistVariableDeclaration); + var iteratorValueExpression = factory.createAssignment(value, boundValue); + var iteratorValueStatement = factory.createExpressionStatement(iteratorValueExpression); + ts.setSourceMapRange(iteratorValueStatement, node.expression); + var exitNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createFalse()); + var exitNonUserCodeStatement = factory.createExpressionStatement(exitNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var enterNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createTrue()); + var enterNonUserCodeStatement = factory.createExpressionStatement(enterNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var statements = []; + var binding = ts.createForOfBindingStatement(factory, node.initializer, value); + statements.push(ts.visitNode(binding, visitor, ts.isStatement)); var bodyLocation; var statementsLocation; - var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); @@ -99320,8 +99539,16 @@ var ts; else { statements.push(statement); } - return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), + var body = ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* EmitFlags.NoSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */); + return factory.createBlock([ + iteratorValueStatement, + exitNonUserCodeStatement, + factory.createTryStatement(body, + /*catchClause*/ undefined, factory.createBlock([ + enterNonUserCodeStatement + ])) + ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ @@ -99332,6 +99559,8 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined); + var nonUserCode = factory.createTempVariable(/*recordTempVariable*/ undefined); + var done = factory.createTempVariable(hoistVariableDeclaration); var errorRecord = factory.createUniqueName("e"); var catchVariable = factory.getGeneratedNameForNode(errorRecord); var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined); @@ -99348,12 +99577,17 @@ var ts; callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement( /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([ + factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()), ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression), factory.createVariableDeclaration(result) ]), node.expression), 2097152 /* EmitFlags.NoHoisting */), - /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), + /*condition*/ factory.inlineExpressions([ + factory.createAssignment(result, createDownlevelAwait(callNext)), + factory.createAssignment(done, getDone), + factory.createLogicalNot(done) + ]), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, getValue)), + /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode)), /*location*/ node), 256 /* EmitFlags.NoTokenTrailingSourceMaps */); ts.setOriginalNode(forStatement, node); return factory.createTryStatement(factory.createBlock([ @@ -99365,7 +99599,7 @@ var ts; ]), 1 /* EmitFlags.SingleLine */)), factory.createBlock([ factory.createTryStatement( /*tryBlock*/ factory.createBlock([ - ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(getDone)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) + ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(factory.createLogicalNot(nonUserCode), factory.createLogicalNot(done)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([ @@ -99521,7 +99755,7 @@ var ts; /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HierarchyFacts.HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); @@ -99532,10 +99766,10 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = factory.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -99664,7 +99898,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ESNextSubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -99741,7 +99975,7 @@ var ts; || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -101210,11 +101444,13 @@ var ts; return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); } function visitIdentifier(node) { - if (!convertedLoopState) { - return node; + if (convertedLoopState) { + if (resolver.isArgumentsLocalBinding(node)) { + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + } } - if (resolver.isArgumentsLocalBinding(node)) { - return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + if (node.hasExtendedUnicodeEscape) { + return ts.setOriginalNode(ts.setTextRange(factory.createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText)), node), node); } return node; } @@ -105361,7 +105597,6 @@ var ts; return node; } function transformAndEmitForInStatement(node) { - // TODO(rbuckton): Source map locations if (containsYield(node)) { // [source] // for (var p in o) { @@ -105369,34 +105604,41 @@ var ts; // } // // [intermediate] - // .local _a, _b, _i - // _a = []; - // for (_b in o) _a.push(_b); + // .local _b, _a, _c, _i + // _b = []; + // _a = o; + // for (_c in _a) _b.push(_c); // _i = 0; // .loop incrementLabel, endLoopLabel // .mark conditionLabel - // .brfalse endLoopLabel, (_i < _a.length) - // p = _a[_i]; + // .brfalse endLoopLabel, (_i < _b.length) + // _c = _b[_i]; + // .brfalse incrementLabel, (_c in _a) + // p = _c; // /*body*/ // .mark incrementLabel - // _b++; + // _c++; // .br conditionLabel // .endloop // .mark endLoopLabel - var keysArray = declareLocal(); // _a - var key = declareLocal(); // _b + var obj = declareLocal(); // _a + var keysArray = declareLocal(); // _b + var key = declareLocal(); // _c var keysIndex = factory.createLoopVariable(); // _i var initializer = node.initializer; hoistVariableDeclaration(keysIndex); + emitAssignment(obj, ts.visitNode(node.expression, visitor, ts.isExpression)); emitAssignment(keysArray, factory.createArrayLiteralExpression()); - emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), + emitStatement(factory.createForInStatement(key, obj, factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), /*typeArguments*/ undefined, [key])))); emitAssignment(keysIndex, factory.createNumericLiteral(0)); var conditionLabel = defineLabel(); var incrementLabel = defineLabel(); - var endLabel = beginLoopBlock(incrementLabel); + var endLoopLabel = beginLoopBlock(incrementLabel); markLabel(conditionLabel); - emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitBreakWhenFalse(endLoopLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitAssignment(key, factory.createElementAccessExpression(keysArray, keysIndex)); + emitBreakWhenFalse(incrementLabel, factory.createBinaryExpression(key, 101 /* SyntaxKind.InKeyword */, obj)); var variable = void 0; if (ts.isVariableDeclarationList(initializer)) { for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { @@ -105409,7 +105651,7 @@ var ts; variable = ts.visitNode(initializer, visitor, ts.isExpression); ts.Debug.assert(ts.isLeftHandSideExpression(variable)); } - emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex)); + emitAssignment(variable, key); transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex))); @@ -107250,7 +107492,7 @@ var ts; return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return createImportCallExpressionCommonJS(argument, containsLexicalThis); + return createImportCallExpressionCommonJS(argument); } } function createImportCallExpressionUMD(arg, containsLexicalThis) { @@ -107273,7 +107515,7 @@ var ts; return factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(arg), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); } @@ -107282,7 +107524,7 @@ var ts; return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, /* isInlineable */ true), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); } @@ -107332,14 +107574,20 @@ var ts; } return promise; } - function createImportCallExpressionCommonJS(arg, containsLexicalThis) { - // import("./blah") + function createImportCallExpressionCommonJS(arg, isInlineable) { + // import(x) // emit as - // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // var _a; + // (_a = x, Promise.resolve().then(() => require(_a)) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); - var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + // If the arg is not inlineable, we have to evaluate it in the current scope with a temp var + var temp = arg && !ts.isSimpleInlineableExpression(arg) && !isInlineable ? factory.createTempVariable(hoistVariableDeclaration) : undefined; + var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), + /*typeArguments*/ undefined, + /*argumentsArray*/ []); + var requireCall = factory.createCallExpression(factory.createIdentifier("require"), + /*typeArguments*/ undefined, temp ? [temp] : arg ? [arg] : []); if (ts.getESModuleInterop(compilerOptions)) { requireCall = emitHelpers().createImportStarHelper(requireCall); } @@ -107360,14 +107608,9 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)])); - // if there is a lexical 'this' in the import call arguments, ensure we indicate - // that this new function expression indicates it captures 'this' so that the - // es2015 transformer will properly substitute 'this' with '_this'. - if (containsLexicalThis) { - ts.setEmitFlags(func, 8 /* EmitFlags.CapturesThis */); - } } - return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + var downleveledImport = factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + return temp === undefined ? downleveledImport : factory.createCommaListExpression([factory.createAssignment(temp, arg), downleveledImport]); } function getHelperExpressionForExport(node, innerExpr) { if (!ts.getESModuleInterop(compilerOptions) || ts.getEmitFlags(node) & 67108864 /* EmitFlags.NeverApplyImportHelper */) { @@ -122540,10 +122783,16 @@ var ts; var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + // We can only reuse emit signatures (i.e. .d.ts signatures) if the .d.ts file is unchanged, + // which will eg be depedent on change in options like declarationDir and outDir options are unchanged. + // We need to look in oldState.compilerOptions, rather than oldCompilerOptions (i.e.we need to disregard useOldState) because + // oldCompilerOptions can be undefined if there was change in say module from None to some other option + // which would make useOldState as false since we can now use reference maps that are needed to track what to emit, what to check etc + // but that option change does not affect d.ts file name so emitSignatures should still be reused. var canCopyEmitSignatures = compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && !outFilePath && - !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); if (useOldState) { // Copy old state's changed files set (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); @@ -123758,7 +124007,7 @@ var ts; var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* CharacterCodes.slash */; if (isNonDirectorySeparatorRoot && dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths - pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart + pathPartForUserCheck.search(/[a-zA-Z]\$\//) === 0) { // Dos style nextPart nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1); if (nextDirectorySeparator === -1) { // ignore "//vda1cs4850/c$/folderAtRoot" @@ -125012,7 +125261,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_36 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -125036,9 +125285,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_12 = _loop_36(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_12 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -125107,7 +125356,7 @@ var ts; } function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - var _loop_37 = function (patternText_1) { + var _loop_36 = function (patternText_1) { var pattern = ts.normalizePath(patternText_1); var indexOfStar = pattern.indexOf("*"); // In module resolution, if `pattern` itself has an extension, a file with that extension is looked up directly, @@ -125174,9 +125423,9 @@ var ts; }; for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { var patternText_1 = _a[_i]; - var state_13 = _loop_37(patternText_1); - if (typeof state_13 === "object") - return state_13.value; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } function validateEnding(_a) { @@ -125264,15 +125513,21 @@ var ts; return undefined; } function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { + var normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPaths === undefined) { + return undefined; + } + var normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePaths = ts.flatMap(normalizedSourcePaths, function (sourcePath) { + return ts.map(normalizedTargetPaths, function (targetPath) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName)); }); + }); + var shortest = ts.min(relativePaths, ts.compareNumberOfDirectorySeparators); + if (!shortest) { return undefined; } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs - ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions) - : ts.removeFileExtension(relativePath); + ? removeExtensionAndIndexPostFix(shortest, ending, compilerOptions) + : ts.removeFileExtension(shortest); } function tryGetModuleNameAsNodeModule(_a, _b, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { var path = _a.path, isRedirect = _a.isRedirect; @@ -125409,8 +125664,8 @@ var ts; } } } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { + function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.mapDefined(rootDirs, function (rootDir) { var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath; }); @@ -127978,8 +128233,15 @@ var ts; } if (buildInfo.program) { // If there are pending changes that are not emitted, project is out of date + // When there are syntax errors, changeFileSet will have list of files changed (irrespective of noEmit) + // But in case of semantic error we need special treatment. + // Checking presence of affectedFilesPendingEmit list is fast and good way to tell if there were semantic errors and file emit was blocked + // But if noEmit is true, affectedFilesPendingEmit will have file list even if there are no semantic errors to preserve list of files to be emitted when running with noEmit false + // So with noEmit set to true, check on semantic diagnostics needs to be explicit as oppose to when it is false when only files pending emit is sufficient if (((_a = buildInfo.program.changeFileSet) === null || _a === void 0 ? void 0 : _a.length) || - (!project.options.noEmit && ((_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length))) { + (!project.options.noEmit ? + (_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length : + ts.some(buildInfo.program.semanticDiagnosticsPerFile, ts.isArray))) { return { type: ts.UpToDateStatusType.OutOfDateBuildInfo, buildInfoFile: buildInfoPath @@ -129160,6 +129422,12 @@ var ts; SemanticClassificationFormat["Original"] = "original"; SemanticClassificationFormat["TwentyTwenty"] = "2020"; })(SemanticClassificationFormat = ts.SemanticClassificationFormat || (ts.SemanticClassificationFormat = {})); + var OrganizeImportsMode; + (function (OrganizeImportsMode) { + OrganizeImportsMode["All"] = "All"; + OrganizeImportsMode["SortAndCombine"] = "SortAndCombine"; + OrganizeImportsMode["RemoveUnused"] = "RemoveUnused"; + })(OrganizeImportsMode = ts.OrganizeImportsMode || (ts.OrganizeImportsMode = {})); var CompletionTriggerKind; (function (CompletionTriggerKind) { /** Completion was triggered by typing an identifier, manual invocation (e.g Ctrl+Space) or via API. */ @@ -130205,6 +130473,8 @@ var ts; return lastTypeNode; } function getContextualTypeFromParentOrAncestorTypeNode(node, checker) { + if (node.flags & (8388608 /* NodeFlags.JSDoc */ & ~262144 /* NodeFlags.JavaScriptFile */)) + return undefined; var contextualType = getContextualTypeFromParent(node, checker); if (contextualType) return contextualType; @@ -132691,6 +132961,10 @@ var ts; return jsx === 2 /* JsxEmit.React */ || jsx === 3 /* JsxEmit.ReactNative */; } ts.jsxModeNeedsExplicitImport = jsxModeNeedsExplicitImport; + function isSourceFileFromLibrary(program, node) { + return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); + } + ts.isSourceFileFromLibrary = isSourceFileFromLibrary; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -135717,7 +135991,7 @@ var ts; if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* CompletionKind.MemberLike */ && - isClassLikeMemberCompletion(symbol, location)) { + isClassLikeMemberCompletion(symbol, location, sourceFile)) { var importAdder = void 0; (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken, formatContext), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder, replacementSpan = _b.replacementSpan); sortText = Completions.SortText.ClassMemberSnippets; // sortText has to be lower priority than the sortText for keywords. See #47852. @@ -135789,7 +136063,7 @@ var ts; data: data, }; } - function isClassLikeMemberCompletion(symbol, location) { + function isClassLikeMemberCompletion(symbol, location, sourceFile) { // TODO: support JS files. if (ts.isInJSFile(location)) { return false; @@ -135823,6 +136097,7 @@ var ts; location.parent.parent && ts.isClassElement(location.parent) && location === location.parent.name && + location.parent.getLastToken(sourceFile) === location.parent.name && ts.isClassLike(location.parent.parent)) || (location.parent && ts.isSyntaxList(location) && @@ -142984,6 +143259,12 @@ var ts; var label = ts.getTargetLabel(node.parent, node.text); return label ? [createDefinitionInfoFromName(typeChecker, label, "label" /* ScriptElementKind.label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 } + if (node.kind === 105 /* SyntaxKind.ReturnKeyword */) { + var functionDeclaration = ts.findAncestor(node.parent, function (n) { + return ts.isClassStaticBlockDeclaration(n) ? "quit" : ts.isFunctionLikeDeclaration(n); + }); + return functionDeclaration ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : undefined; + } if (ts.isStaticModifier(node) && ts.isClassStaticBlockDeclaration(node.parent)) { var classDecl = node.parent.parent; var _c = getSymbol(classDecl, typeChecker, stopAtAlias), symbol_1 = _c.symbol, failedAliasResolution_1 = _c.failedAliasResolution; @@ -143119,13 +143400,16 @@ var ts; if (!baseDeclaration) return; var baseTypeNode = ts.getEffectiveBaseTypeNode(baseDeclaration); - var baseType = baseTypeNode ? typeChecker.getTypeAtLocation(baseTypeNode) : undefined; - if (!baseType) + if (!baseTypeNode) + return; + var expression = ts.skipParentheses(baseTypeNode.expression); + var base = ts.isClassExpression(expression) ? expression.symbol : typeChecker.getSymbolAtLocation(expression); + if (!base) return; var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(classElement.name)); var symbol = ts.hasStaticModifier(classElement) - ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbolAtLocation(baseType.symbol, baseDeclaration), name) - : typeChecker.getPropertyOfType(baseType, name); + ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbol(base), name) + : typeChecker.getPropertyOfType(typeChecker.getDeclaredTypeOfSymbol(base), name); if (!symbol) return; return getDefinitionFromSymbol(typeChecker, symbol, node); @@ -143832,19 +144116,24 @@ var ts; return getCommentOwnerInfoWorker(commentOwner.initializer, options); case 260 /* SyntaxKind.ClassDeclaration */: case 261 /* SyntaxKind.InterfaceDeclaration */: - case 168 /* SyntaxKind.PropertySignature */: case 263 /* SyntaxKind.EnumDeclaration */: case 302 /* SyntaxKind.EnumMember */: case 262 /* SyntaxKind.TypeAliasDeclaration */: return { commentOwner: commentOwner }; + case 168 /* SyntaxKind.PropertySignature */: { + var host_1 = commentOwner; + return host_1.type && ts.isFunctionTypeNode(host_1.type) + ? { commentOwner: commentOwner, parameters: host_1.type.parameters, hasReturn: hasReturn(host_1.type, options) } + : { commentOwner: commentOwner }; + } case 240 /* SyntaxKind.VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; - var host_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + var host_2 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } + return host_2 + ? { commentOwner: commentOwner, parameters: host_2.parameters, hasReturn: hasReturn(host_2, options) } : { commentOwner: commentOwner }; } case 308 /* SyntaxKind.SourceFile */: @@ -143874,7 +144163,7 @@ var ts; } function hasReturn(node, options) { return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && - (ts.isArrowFunction(node) && ts.isExpression(node.body) + (ts.isFunctionTypeNode(node) || ts.isArrowFunction(node) && ts.isExpression(node.body) || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { @@ -144915,23 +145204,39 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { + function organizeImports(sourceFile, formatContext, host, program, preferences, mode) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var shouldSort = mode === "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ || mode === "All" /* OrganizeImportsMode.All */; + var shouldCombine = shouldSort; // These are currently inseparable, but I draw a distinction for clarity and in case we add modes in the future. + var shouldRemove = mode === "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */ || mode === "All" /* OrganizeImportsMode.All */; + var maybeRemove = shouldRemove ? removeUnusedImports : ts.identity; + var maybeCoalesce = shouldCombine ? coalesceImports : ts.identity; + var processImportsOfSameModuleSpecifier = function (importGroup) { + var processedDeclarations = maybeCoalesce(maybeRemove(importGroup, sourceFile, program)); + return shouldSort + ? ts.stableSort(processedDeclarations, function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }) + : processedDeclarations; + }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, sourceFile.statements.filter(ts.isImportDeclaration)); - topLevelImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, coalesceAndOrganizeImports); }); - // All of the old ExportDeclarations in the file, in syntactic order. - var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); - organizeImportsWorker(topLevelExportDecls, coalesceExports); + topLevelImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier); }); + // Exports are always used + if (mode !== "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */) { + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); + } for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; if (!ambientModule.body) continue; var ambientModuleImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, ambientModule.body.statements.filter(ts.isImportDeclaration)); - ambientModuleImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, coalesceAndOrganizeImports); }); - var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); - organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + ambientModuleImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier); }); + // Exports are always used + if (mode !== "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */) { + var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + } } return changeTracker.getChanges(); function organizeImportsWorker(oldImportDecls, coalesce) { @@ -144944,8 +145249,12 @@ var ts; // Consider: we could do a more careful check that this trivia is actually a header, // but the consequences of being wrong are very minor. ts.suppressLeadingTrivia(oldImportDecls[0]); - var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); - var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var oldImportGroups = shouldCombine + ? ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }) + : [oldImportDecls]; + var sortedImportGroups = shouldSort + ? ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }) + : oldImportGroups; var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) ? coalesce(importGroup) @@ -145009,11 +145318,7 @@ var ts; } return false; } - function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { - // As a precaution, consider unused import detection to be destructive (GH #43051) - if (skipDestructiveCodeActions) { - return oldImports; - } + function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); @@ -145869,7 +146174,7 @@ var ts; return bestMatch; } function betterMatch(a, b) { - return ts.min(a, b, compareMatches); + return ts.min([a, b], compareMatches); } function compareMatches(a, b) { return a === undefined ? 1 /* Comparison.GreaterThan */ : b === undefined ? -1 /* Comparison.LessThan */ @@ -146478,8 +146783,8 @@ var ts; } if (ts.scanner.getToken() === 15 /* SyntaxKind.TemplateHead */) { var stack = [ts.scanner.getToken()]; - var token = ts.scanner.scan(); loop: while (ts.length(stack)) { + var token = ts.scanner.scan(); switch (token) { case 1 /* SyntaxKind.EndOfFileToken */: break loop; @@ -146507,7 +146812,6 @@ var ts; } break; } - token = ts.scanner.scan(); } nextToken(); } @@ -148986,7 +149290,7 @@ var ts; tags = signature.getJsDocTags(); if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) { documentation = allSignatures[0].getDocumentationComment(typeChecker); - tags = allSignatures[0].getJsDocTags(); + tags = allSignatures[0].getJsDocTags().filter(function (tag) { return tag.name !== "deprecated"; }); // should only include @deprecated JSDoc tag on the first overload (#49368) } } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -149329,7 +149633,7 @@ var ts; return false; } function shouldRescanJsxText(node) { - return ts.isJsxText(node); + return ts.isJsxText(node) || ts.isJsxElement(node) && (lastTokenInfo === null || lastTokenInfo === void 0 ? void 0 : lastTokenInfo.token.kind) === 11 /* SyntaxKind.JsxText */; } function shouldRescanSlashToken(container) { return container.kind === 13 /* SyntaxKind.RegularExpressionLiteral */; @@ -150098,10 +150402,10 @@ var ts; !nodeIsInDecoratorContext(context.nextTokenParent); } function nodeIsInDecoratorContext(node) { - while (ts.isExpressionNode(node)) { + while (node && ts.isExpression(node)) { node = node.parent; } - return node.kind === 167 /* SyntaxKind.Decorator */; + return node && node.kind === 167 /* SyntaxKind.Decorator */; } function isStartOfVariableDeclarationList(context) { return context.currentTokenParent.kind === 258 /* SyntaxKind.VariableDeclarationList */ && @@ -153019,6 +153323,26 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } + function endPositionToDeleteNodeInList(sourceFile, node, prevNode, nextNode) { + var end = startPositionToDeleteNodeInList(sourceFile, nextNode); + if (prevNode === undefined || ts.positionsAreOnSameLine(getAdjustedEndPosition(sourceFile, node, {}), end, sourceFile)) { + return end; + } + var token = ts.findPrecedingToken(nextNode.getStart(sourceFile), sourceFile); + if (isSeparator(node, token)) { + var prevToken = ts.findPrecedingToken(node.getStart(sourceFile), sourceFile); + if (isSeparator(prevNode, prevToken)) { + var pos = ts.skipTrivia(sourceFile.text, token.getEnd(), /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + if (ts.positionsAreOnSameLine(prevToken.getStart(sourceFile), token.getStart(sourceFile), sourceFile)) { + return ts.isLineBreak(sourceFile.text.charCodeAt(pos - 1)) ? pos - 1 : pos; + } + if (ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { + return pos; + } + } + } + return end; + } function getClassOrObjectBraceEnds(cls, sourceFile) { var open = ts.findChildOfKind(cls, 18 /* SyntaxKind.OpenBraceToken */, sourceFile); var close = ts.findChildOfKind(cls, 19 /* SyntaxKind.CloseBraceToken */, sourceFile); @@ -153576,7 +153900,7 @@ var ts; deletedNodesInLists.add(node); changes.deleteRange(sourceFile, { pos: startPositionToDeleteNodeInList(sourceFile, node), - end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : endPositionToDeleteNodeInList(sourceFile, node, containingList[index - 1], containingList[index + 1]), }); } })(textChanges = ts.textChanges || (ts.textChanges = {})); @@ -154046,6 +154370,15 @@ var ts; }); } function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { + if (ts.isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) { + var exprType = checker.getTypeAtLocation(insertionSite); + var asyncIter = checker.getAsyncIterableType(); + if (asyncIter && checker.isTypeAssignableTo(exprType, asyncIter)) { + var forOf = insertionSite.parent; + changeTracker.replaceNode(sourceFile, forOf, ts.factory.updateForOfStatement(forOf, ts.factory.createToken(133 /* SyntaxKind.AwaitKeyword */), forOf.initializer, forOf.expression, forOf.statement)); + return; + } + } if (ts.isBinaryExpression(insertionSite)) { for (var _i = 0, _a = [insertionSite.left, insertionSite.right]; _i < _a.length; _i++) { var side = _a[_i]; @@ -157771,6 +158104,143 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixImportNonExportedMember"; + var errorCodes = [ + ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixId], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program; + var info = getInfo(sourceFile, span.start, program); + if (info === undefined) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, program, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId, ts.Diagnostics.Export_all_referenced_locals)]; + }, + getAllCodeActions: function (context) { + var program = context.program; + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var exports = new ts.Map(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, program); + if (info === undefined) + return undefined; + var exportName = info.exportName, node = info.node, moduleSourceFile = info.moduleSourceFile; + if (tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly) === undefined && ts.canHaveExportModifier(node)) { + changes.insertExportModifier(moduleSourceFile, node); + } + else { + var moduleExports = exports.get(moduleSourceFile) || { typeOnlyExports: [], exports: [] }; + if (exportName.isTypeOnly) { + moduleExports.typeOnlyExports.push(exportName); + } + else { + moduleExports.exports.push(exportName); + } + exports.set(moduleSourceFile, moduleExports); + } + }); + exports.forEach(function (moduleExports, moduleSourceFile) { + var exportDeclaration = tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ true); + if (exportDeclaration && exportDeclaration.isTypeOnly) { + doChanges(changes, program, moduleSourceFile, moduleExports.typeOnlyExports, exportDeclaration); + doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ false)); + } + else { + doChanges(changes, program, moduleSourceFile, __spreadArray(__spreadArray([], moduleExports.exports, true), moduleExports.typeOnlyExports, true), exportDeclaration); + } + }); + })); + } + }); + function getInfo(sourceFile, pos, program) { + var _a; + var token = ts.getTokenAtPosition(sourceFile, pos); + if (ts.isIdentifier(token)) { + var importDeclaration = ts.findAncestor(token, ts.isImportDeclaration); + if (importDeclaration === undefined) + return undefined; + var moduleSpecifier = ts.isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier.text : undefined; + if (moduleSpecifier === undefined) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, moduleSpecifier, /*mode*/ undefined); + if (resolvedModule === undefined) + return undefined; + var moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName); + if (moduleSourceFile === undefined || ts.isSourceFileFromLibrary(program, moduleSourceFile)) + return undefined; + var moduleSymbol = moduleSourceFile.symbol; + var locals = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals; + if (locals === undefined) + return undefined; + var localSymbol = locals.get(token.escapedText); + if (localSymbol === undefined) + return undefined; + var node = getNodeOfSymbol(localSymbol); + if (node === undefined) + return undefined; + var exportName = { node: token, isTypeOnly: ts.isTypeDeclaration(node) }; + return { exportName: exportName, node: node, moduleSourceFile: moduleSourceFile, moduleSpecifier: moduleSpecifier }; + } + return undefined; + } + function doChange(changes, program, _a) { + var exportName = _a.exportName, node = _a.node, moduleSourceFile = _a.moduleSourceFile; + var exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); + if (exportDeclaration) { + updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]); + } + else if (ts.canHaveExportModifier(node)) { + changes.insertExportModifier(moduleSourceFile, node); + } + else { + createExport(changes, program, moduleSourceFile, [exportName]); + } + } + function doChanges(changes, program, sourceFile, moduleExports, node) { + if (ts.length(moduleExports)) { + if (node) { + updateExport(changes, program, sourceFile, node, moduleExports); + } + else { + createExport(changes, program, sourceFile, moduleExports); + } + } + } + function tryGetExportDeclaration(sourceFile, isTypeOnly) { + var predicate = function (node) { + return ts.isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); + }; + return ts.findLast(sourceFile.statements, predicate); + } + function updateExport(changes, program, sourceFile, node, names) { + var namedExports = node.exportClause && ts.isNamedExports(node.exportClause) ? node.exportClause.elements : ts.factory.createNodeArray([]); + var allowTypeModifier = !node.isTypeOnly && !!(program.getCompilerOptions().isolatedModules || ts.find(namedExports, function (e) { return e.isTypeOnly; })); + changes.replaceNode(sourceFile, node, ts.factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, ts.factory.createNamedExports(ts.factory.createNodeArray(__spreadArray(__spreadArray([], namedExports, true), createExportSpecifiers(names, allowTypeModifier), true), /*hasTrailingComma*/ namedExports.hasTrailingComma)), node.moduleSpecifier, node.assertClause)); + } + function createExport(changes, program, sourceFile, names) { + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ !!program.getCompilerOptions().isolatedModules)), /*moduleSpecifier*/ undefined, /*assertClause*/ undefined)); + } + function createExportSpecifiers(names, allowTypeModifier) { + return ts.factory.createNodeArray(ts.map(names, function (n) { return ts.factory.createExportSpecifier(allowTypeModifier && n.isTypeOnly, /*propertyName*/ undefined, n.node); })); + } + function getNodeOfSymbol(symbol) { + if (symbol.valueDeclaration === undefined) { + return ts.firstOrUndefined(symbol.declarations); + } + var declaration = symbol.valueDeclaration; + var variableStatement = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : undefined; + return variableStatement && ts.length(variableStatement.declarationList.declarations) === 1 ? variableStatement : declaration; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -158301,7 +158771,7 @@ var ts; var argIndex = ts.findIndex(parent.parent.arguments, function (arg) { return arg === parent; }); if (argIndex < 0) return undefined; - var signature = ts.singleOrUndefined(checker.getSignaturesOfType(checker.getTypeAtLocation(parent.parent.expression), 0 /* SignatureKind.Call */)); + var signature = checker.getResolvedSignature(parent.parent); if (!(signature && signature.declaration && signature.parameters[argIndex])) return undefined; var param = signature.parameters[argIndex].valueDeclaration; @@ -158348,13 +158818,13 @@ var ts; if (ts.isIdentifier(token) && ts.isCallExpression(parent.parent)) { var moduleDeclaration = ts.find(symbol.declarations, ts.isModuleDeclaration); var moduleDeclarationSourceFile = moduleDeclaration === null || moduleDeclaration === void 0 ? void 0 : moduleDeclaration.getSourceFile(); - if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { + if (moduleDeclaration && moduleDeclarationSourceFile && !ts.isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { return { kind: InfoKind.Function, token: token, call: parent.parent, sourceFile: sourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleDeclaration }; } var moduleSourceFile = ts.find(symbol.declarations, ts.isSourceFile); if (sourceFile.commonJsModuleIndicator) return undefined; - if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) { + if (moduleSourceFile && !ts.isSourceFileFromLibrary(program, moduleSourceFile)) { return { kind: InfoKind.Function, token: token, call: parent.parent, sourceFile: moduleSourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleSourceFile }; } } @@ -158364,7 +158834,7 @@ var ts; return undefined; // Prefer to change the class instead of the interface if they are merged var declaration = classDeclaration || ts.find(symbol.declarations, function (d) { return ts.isInterfaceDeclaration(d) || ts.isTypeLiteralNode(d); }); - if (declaration && !isSourceFileFromLibrary(program, declaration.getSourceFile())) { + if (declaration && !ts.isSourceFileFromLibrary(program, declaration.getSourceFile())) { var makeStatic = !ts.isTypeLiteralNode(declaration) && (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); if (makeStatic && (ts.isPrivateIdentifier(token) || ts.isInterfaceDeclaration(declaration))) return undefined; @@ -158376,14 +158846,11 @@ var ts; return { kind: InfoKind.TypeLikeDeclaration, token: token, call: call, modifierFlags: modifierFlags, parentDeclaration: declaration, declSourceFile: declSourceFile, isJSFile: isJSFile }; } var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); - if (enumDeclaration && !(leftExpressionType.flags & 1056 /* TypeFlags.EnumLike */) && !ts.isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { + if (enumDeclaration && !(leftExpressionType.flags & 1056 /* TypeFlags.EnumLike */) && !ts.isPrivateIdentifier(token) && !ts.isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { return { kind: InfoKind.Enum, token: token, parentDeclaration: enumDeclaration }; } return undefined; } - function isSourceFileFromLibrary(program, node) { - return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); - } function getActionsForMissingMemberDeclaration(context, info) { return info.isJSFile ? ts.singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : createActionsForAddMissingMemberInTypeScriptFile(context, info); @@ -163809,8 +164276,8 @@ var ts; var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; - var description = functionExtraction.description; if (refactor.refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + var description = functionExtraction.description; if (functionExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will @@ -163834,15 +164301,15 @@ var ts; } } if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + var description = constantExtraction.description; if (constantExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will // preferentially go into nearer scopes - var description_1 = constantExtraction.description; - if (!usedConstantNames.has(description_1)) { - usedConstantNames.set(description_1, true); + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); constantActions.push({ - description: description_1, + description: description, name: "constant_scope_".concat(i), kind: extractConstantAction.kind }); @@ -163987,7 +164454,6 @@ var ts; var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, adjustedSpan); // Do the same for the ending position var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, adjustedSpan); - var declarations = []; // We'll modify these flags as we walk the tree to collect data // about what things need to be done as part of the extraction. var rangeFacts = RangeFacts.None; @@ -164030,7 +164496,7 @@ var ts; // the expression. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } - return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations, thisNode: thisNode } }; + return { targetRange: { range: statements, facts: rangeFacts, thisNode: thisNode } }; } if (ts.isReturnStatement(start) && !start.expression) { // Makes no sense to extract an expression-less return statement. @@ -164042,7 +164508,7 @@ var ts; if (errors) { return { errors: errors }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations, thisNode: thisNode } }; // TODO: GH#18217 + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode: thisNode } }; // TODO: GH#18217 /** * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. * @param node The unrefined extraction node. @@ -164054,10 +164520,10 @@ var ts; } } else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { - var declarations_6 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; + var declarations = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, declarations_5 = declarations_6; _i < declarations_5.length; _i++) { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; if (declaration.initializer) { numInitializers++; @@ -164157,7 +164623,6 @@ var ts; (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } - declarations.push(node.symbol); } // Some things can't be extracted in certain situations switch (node.kind) { @@ -165882,7 +166347,7 @@ var ts; function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); var prologueDirectives = ts.takeWhile(oldFile.statements, ts.isPrologueDirective); - if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + if (oldFile.externalModuleIndicator === undefined && oldFile.commonJsModuleIndicator === undefined && usage.oldImportsNeededByNewFile.size() === 0) { deleteMovedStatements(oldFile, toMove.ranges, changes); return __spreadArray(__spreadArray([], prologueDirectives, true), toMove.all, true); } @@ -166123,7 +166588,12 @@ var ts; switch (name.kind) { case 79 /* SyntaxKind.Identifier */: if (isUnused(name)) { - changes.delete(sourceFile, name); + if (varDecl.initializer && ts.isRequireCall(varDecl.initializer, /*requireStringLiteralLikeArgument*/ true)) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && ts.length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); + } + else { + changes.delete(sourceFile, name); + } } break; case 204 /* SyntaxKind.ArrayBindingPattern */: @@ -166355,6 +166825,9 @@ var ts; ts.copyEntries(this.map, clone.map); return clone; }; + SymbolSet.prototype.size = function () { + return this.map.size; + }; return SymbolSet; }()); function isTopLevelDeclaration(node) { @@ -166443,7 +166916,8 @@ var ts; if (useEs6Exports) { return !ts.isExpressionStatement(decl) && ts.hasSyntacticModifier(decl, 1 /* ModifierFlags.Export */) || !!(name && ((_a = sourceFile.symbol.exports) === null || _a === void 0 ? void 0 : _a.has(name.escapedText))); } - return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + return !!sourceFile.symbol && !!sourceFile.symbol.exports && + getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); } function addExport(decl, useEs6Exports) { return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); @@ -168203,8 +168677,8 @@ var ts; tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); } }; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; _loop_20(declaration); } } @@ -168230,8 +168704,8 @@ var ts; if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); }; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; _loop_21(declaration); } } @@ -169401,12 +169875,14 @@ var ts; return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } function organizeImports(args, formatOptions, preferences) { + var _a; if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(args.type === "file"); var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); + var mode = (_a = args.mode) !== null && _a !== void 0 ? _a : (args.skipDestructiveCodeActions ? "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ : "All" /* OrganizeImportsMode.All */); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, mode); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -171986,6 +172462,12 @@ var ts; CommandTypes["ProvideInlayHints"] = "provideInlayHints"; // NOTE: If updating this, be sure to also update `allCommandNames` in `testRunner/unittests/tsserver/session.ts`. })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {})); + var OrganizeImportsMode; + (function (OrganizeImportsMode) { + OrganizeImportsMode["All"] = "All"; + OrganizeImportsMode["SortAndCombine"] = "SortAndCombine"; + OrganizeImportsMode["RemoveUnused"] = "RemoveUnused"; + })(OrganizeImportsMode = protocol.OrganizeImportsMode || (protocol.OrganizeImportsMode = {})); var WatchFileKind; (function (WatchFileKind) { WatchFileKind["FixedPollingInterval"] = "FixedPollingInterval"; @@ -172872,6 +173354,7 @@ var ts; this.watchOptions = watchOptions; this.rootFiles = []; this.rootFilesMap = new ts.Map(); + /*@internal*/ this.plugins = []; /*@internal*/ /** @@ -173400,6 +173883,7 @@ var ts; this.directoryStructureHost = undefined; this.exportMapCache = undefined; this.projectErrors = undefined; + this.plugins.length = 0; // Clean up file watchers waiting for missing files if (this.missingFilesMap) { ts.clearMap(this.missingFilesMap, ts.closeFileWatcher); @@ -174073,35 +174557,39 @@ var ts; Project.prototype.isSourceOfProjectReferenceRedirect = function (fileName) { return !!this.program && this.program.isSourceOfProjectReferenceRedirect(fileName); }; + /*@internal*/ + Project.prototype.getGlobalPluginSearchPaths = function () { + // Search any globally-specified probe paths, then our peer node_modules + return __spreadArray(__spreadArray([], this.projectService.pluginProbeLocations, true), [ + // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ + ts.combinePaths(this.projectService.getExecutingFilePath(), "../../.."), + ], false); + }; Project.prototype.enableGlobalPlugins = function (options, pluginConfigOverrides) { + if (!this.projectService.globalPlugins.length) + return; var host = this.projectService.host; if (!host.require && !host.importPlugin) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } - // Search any globally-specified probe paths, then our peer node_modules - var searchPaths = __spreadArray(__spreadArray([], this.projectService.pluginProbeLocations, true), [ - // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ - ts.combinePaths(this.projectService.getExecutingFilePath(), "../../.."), - ], false); - if (this.projectService.globalPlugins) { - var _loop_1 = function (globalPluginName) { - // Skip empty names from odd commandline parses - if (!globalPluginName) - return "continue"; - // Skip already-locally-loaded plugins - if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) - return "continue"; - // Provide global: true so plugins can detect why they can't find their config - this_1.projectService.logger.info("Loading global plugin ".concat(globalPluginName)); - this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides); - }; - var this_1 = this; - // Enable global plugins with synthetic configuration entries - for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { - var globalPluginName = _a[_i]; - _loop_1(globalPluginName); - } + // Enable global plugins with synthetic configuration entries + var searchPaths = this.getGlobalPluginSearchPaths(); + var _loop_1 = function (globalPluginName) { + // Skip empty names from odd commandline parses + if (!globalPluginName) + return "continue"; + // Skip already-locally-loaded plugins + if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) + return "continue"; + // Provide global: true so plugins can detect why they can't find their config + this_1.projectService.logger.info("Loading global plugin ".concat(globalPluginName)); + this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides); + }; + var this_1 = this; + for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { + var globalPluginName = _a[_i]; + _loop_1(globalPluginName); } }; /** @@ -174832,14 +175320,16 @@ var ts; }; /*@internal*/ ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) { + var _a; + this.plugins.length = 0; + if (!((_a = options.plugins) === null || _a === void 0 ? void 0 : _a.length) && !this.projectService.globalPlugins.length) + return; var host = this.projectService.host; if (!host.require && !host.importPlugin) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; } - // Search our peer node_modules, then any globally-specified probe paths - // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ - var searchPaths = __spreadArray([ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")], this.projectService.pluginProbeLocations, true); + var searchPaths = this.getGlobalPluginSearchPaths(); if (this.projectService.allowLocalPluginLoads) { var local = ts.getDirectoryPath(this.canonicalConfigFilePath); this.projectService.logger.info("Local plugin loading enabled; adding ".concat(local, " to search paths")); @@ -174847,8 +175337,8 @@ var ts; } // Enable tsconfig-specified plugins if (options.plugins) { - for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) { - var pluginConfigEntry = _a[_i]; + for (var _i = 0, _b = options.plugins; _i < _b.length; _i++) { + var pluginConfigEntry = _b[_i]; this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); } } @@ -175693,18 +176183,20 @@ var ts; return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName); }; /* @internal */ - ProjectService.prototype.tryGetDefaultProjectForFile = function (fileName) { - var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + ProjectService.prototype.tryGetDefaultProjectForFile = function (fileNameOrScriptInfo) { + var scriptInfo = ts.isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined; }; /* @internal */ - ProjectService.prototype.ensureDefaultProjectForFile = function (fileName) { - return this.tryGetDefaultProjectForFile(fileName) || this.doEnsureDefaultProjectForFile(fileName); + ProjectService.prototype.ensureDefaultProjectForFile = function (fileNameOrScriptInfo) { + return this.tryGetDefaultProjectForFile(fileNameOrScriptInfo) || this.doEnsureDefaultProjectForFile(fileNameOrScriptInfo); }; - ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileName) { + ProjectService.prototype.doEnsureDefaultProjectForFile = function (fileNameOrScriptInfo) { this.ensureProjectStructuresUptoDate(); - var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); - return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(fileName), server.Errors.ThrowNoProject()); + var scriptInfo = ts.isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; + return scriptInfo ? + scriptInfo.getDefaultProject() : + (this.logErrorForScriptInfoNotFound(ts.isString(fileNameOrScriptInfo) ? fileNameOrScriptInfo : fileNameOrScriptInfo.fileName), server.Errors.ThrowNoProject()); }; ProjectService.prototype.getScriptInfoEnsuringProjectsUptoDate = function (uncheckedFileName) { this.ensureProjectStructuresUptoDate(); @@ -177876,7 +178368,7 @@ var ts; if (this.serverMode !== ts.LanguageServiceMode.Semantic || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { return; } - var project = scriptInfo.getDefaultProject(); + var project = this.ensureDefaultProjectForFile(scriptInfo); if (!project.languageServiceEnabled) { return; } @@ -180476,6 +180968,10 @@ var ts; this.projectService.logErrorForScriptInfoNotFound(args.file); return server.Errors.ThrowNoProject(); } + else if (!getScriptInfoEnsuringProjectsUptoDate) { + // Ensure there are containing projects are present + this.projectService.ensureDefaultProjectForFile(scriptInfo); + } projects = scriptInfo.containingProjects; symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); } @@ -180544,6 +181040,7 @@ var ts; var references = getReferencesWorker(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, this.logger); if (!simplifiedResult) return references; + var preferences = this.getPreferences(file); var defaultProject = this.getDefaultProject(args); var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); @@ -180552,7 +181049,7 @@ var ts; var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; var symbolName = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : ""; var refs = ts.flatMap(references, function (referencedSymbol) { - return referencedSymbol.references.map(function (entry) { return referenceEntryToReferencesResponseItem(_this.projectService, entry); }); + return referencedSymbol.references.map(function (entry) { return referenceEntryToReferencesResponseItem(_this.projectService, entry, preferences); }); }); return { refs: refs, symbolName: symbolName, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString }; }; @@ -180560,6 +181057,7 @@ var ts; var _this = this; var projects = this.getProjects(args); var fileName = args.file; + var preferences = this.getPreferences(server.toNormalizedPath(fileName)); var references = []; var seen = createDocumentSpanSet(); forEachProjectInProjects(projects, /*path*/ undefined, function (project) { @@ -180578,7 +181076,7 @@ var ts; }); if (!simplifiedResult) return references; - var refs = references.map(function (entry) { return referenceEntryToReferencesResponseItem(_this.projectService, entry); }); + var refs = references.map(function (entry) { return referenceEntryToReferencesResponseItem(_this.projectService, entry, preferences); }); return { refs: refs, symbolName: "\"".concat(args.file, "\"") @@ -180602,13 +181100,7 @@ var ts; return this.getFileAndProjectWorker(args.file, args.projectFileName); }; Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) { - // Since this is syntactic operation, there should always be project for the file - // throw if we dont get project - var file = server.toNormalizedPath(args.file); - var project = this.getProject(args.projectFileName) || this.projectService.ensureDefaultProjectForFile(file); - if (!project) { - return server.Errors.ThrowNoProject(); - } + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; return { file: file, languageService: project.getLanguageService(/*ensureSynchronized*/ false) @@ -181149,11 +181641,12 @@ var ts; } }; Session.prototype.organizeImports = function (args, simplifiedResult) { + var _a; ts.Debug.assert(args.scope.type === "file"); - var _a = this.getFileAndProject(args.scope.args), file = _a.file, project = _a.project; + var _b = this.getFileAndProject(args.scope.args), file = _b.file, project = _b.project; var changes = project.getLanguageService().organizeImports({ fileName: file, - skipDestructiveCodeActions: args.skipDestructiveCodeActions, + mode: (_a = args.mode) !== null && _a !== void 0 ? _a : (args.skipDestructiveCodeActions ? "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ : undefined), type: "file", }, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { @@ -181647,14 +182140,18 @@ var ts; } return text; } - function referenceEntryToReferencesResponseItem(projectService, _a) { + function referenceEntryToReferencesResponseItem(projectService, _a, _b) { var fileName = _a.fileName, textSpan = _a.textSpan, contextSpan = _a.contextSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition; + var disableLineTextInReferences = _b.disableLineTextInReferences; var scriptInfo = ts.Debug.checkDefined(projectService.getScriptInfo(fileName)); var span = toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo); - var lineSpan = scriptInfo.lineToTextSpan(span.start.line - 1); - var lineText = scriptInfo.getSnapshot().getText(lineSpan.start, ts.textSpanEnd(lineSpan)).replace(/\r|\n/g, ""); + var lineText = disableLineTextInReferences ? undefined : getLineText(scriptInfo, span); return __assign(__assign({ file: fileName }, span), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition }); } + function getLineText(scriptInfo, span) { + var lineSpan = scriptInfo.lineToTextSpan(span.start.line - 1); + return scriptInfo.getSnapshot().getText(lineSpan.start, ts.textSpanEnd(lineSpan)).replace(/\r|\n/g, ""); + } function isCompletionEntryData(data) { return data === undefined || data && typeof data === "object" && typeof data.exportName === "string" diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 0e6b2559af02e..54e4c654e3588 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -5399,9 +5399,9 @@ declare namespace ts { /** If provided, called with Diagnostic message that informs about change in watch status */ onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions, errorCount?: number): void; /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: CompilerOptions): FileWatcher; + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: CompilerOptions): FileWatcher; + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; /** If provided, will be used to reset existing delayed compilation */ @@ -6032,8 +6032,15 @@ declare namespace ts { type: "file"; fileName: string; } + enum OrganizeImportsMode { + All = "All", + SortAndCombine = "SortAndCombine", + RemoveUnused = "RemoveUnused" + } interface OrganizeImportsArgs extends CombinedCodeFixScope { + /** @deprecated Use `mode` instead */ skipDestructiveCodeActions?: boolean; + mode?: OrganizeImportsMode; } type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; enum CompletionTriggerKind { diff --git a/lib/typescript.js b/lib/typescript.js index 947429a3943b6..a1370cc514c7b 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -99,7 +99,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 = "".concat(ts.versionMajorMinor, ".1-beta"); + ts.version = "".concat(ts.versionMajorMinor, ".2-rc"); /* @internal */ var Comparison; (function (Comparison) { @@ -1891,8 +1891,8 @@ var ts; return compareValues(a === null || a === void 0 ? void 0 : a.start, b === null || b === void 0 ? void 0 : b.start) || compareValues(a === null || a === void 0 ? void 0 : a.length, b === null || b === void 0 ? void 0 : b.length); } ts.compareTextSpans = compareTextSpans; - function min(a, b, compare) { - return compare(a, b) === -1 /* Comparison.LessThan */ ? a : b; + function min(items, compare) { + return reduceLeft(items, function (x, y) { return compare(x, y) === -1 /* Comparison.LessThan */ ? x : y; }); } ts.min = min; /** @@ -3205,11 +3205,13 @@ var ts; // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers // > MUST NOT include leading zeroes. var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; // https://semver.org/#spec-item-10 // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated // > identifiers immediately following the patch or pre-release version. Identifiers MUST // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var buildPartRegExp = /^[a-z0-9-]+$/i; // https://semver.org/#spec-item-9 // > Numeric identifiers MUST NOT include leading zeroes. var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; @@ -3229,13 +3231,15 @@ var ts; ts.Debug.assert(major >= 0, "Invalid argument: major"); ts.Debug.assert(minor >= 0, "Invalid argument: minor"); ts.Debug.assert(patch >= 0, "Invalid argument: patch"); - ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); - ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + var prereleaseArray = prerelease ? ts.isArray(prerelease) ? prerelease : prerelease.split(".") : ts.emptyArray; + var buildArray = build ? ts.isArray(build) ? build : build.split(".") : ts.emptyArray; + ts.Debug.assert(ts.every(prereleaseArray, function (s) { return prereleasePartRegExp.test(s); }), "Invalid argument: prerelease"); + ts.Debug.assert(ts.every(buildArray, function (s) { return buildPartRegExp.test(s); }), "Invalid argument: build"); this.major = major; this.minor = minor; this.patch = patch; - this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; - this.build = build ? build.split(".") : ts.emptyArray; + this.prerelease = prereleaseArray; + this.build = buildArray; } Version.tryParse = function (text) { var result = tryParseComponents(text); @@ -3274,6 +3278,10 @@ var ts; default: return ts.Debug.assertNever(field); } }; + Version.prototype.with = function (fields) { + var _a = fields.major, major = _a === void 0 ? this.major : _a, _b = fields.minor, minor = _b === void 0 ? this.minor : _b, _c = fields.patch, patch = _c === void 0 ? this.patch : _c, _d = fields.prerelease, prerelease = _d === void 0 ? this.prerelease : _d, _e = fields.build, build = _e === void 0 ? this.build : _e; + return new Version(major, minor, patch, prerelease, build); + }; Version.prototype.toString = function () { var result = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); if (ts.some(this.prerelease)) @@ -3282,7 +3290,7 @@ var ts; result += "+".concat(this.build.join(".")); return result; }; - Version.zero = new Version(0, 0, 0); + Version.zero = new Version(0, 0, 0, ["0"]); return Version; }()); ts.Version = Version; @@ -3365,6 +3373,10 @@ var ts; } return undefined; }; + /** + * Tests whether a version matches the range. This is equivalent to `satisfies(version, range, { includePrerelease: true })`. + * in `node-semver`. + */ VersionRange.prototype.test = function (version) { if (typeof version === "string") version = new Version(version); @@ -3475,19 +3487,20 @@ var ts; break; case "<": case ">=": - comparators.push(createComparator(operator, version)); + comparators.push(isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version.with({ prerelease: "0" })) : + createComparator(operator, version)); break; case "<=": case ">": - comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : - isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major").with({ prerelease: "0" })) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor").with({ prerelease: "0" })) : createComparator(operator, version)); break; case "=": case undefined: if (isWildcard(minor) || isWildcard(patch)) { - comparators.push(createComparator(">=", version)); - comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + comparators.push(createComparator(">=", version.with({ prerelease: "0" }))); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor").with({ prerelease: "0" }))); } else { comparators.push(createComparator("=", version)); @@ -5096,8 +5109,8 @@ var ts; NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAccessInAsync"] = 2048] = "MethodWithSuperPropertyAccessInAsync"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAssignmentInAsync"] = 4096] = "MethodWithSuperPropertyAssignmentInAsync"; NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; @@ -6732,7 +6745,7 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; + var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; var pollingWatches = new ts.Map(); var fsWatches = new ts.Map(); var fsWatchesRecursive = new ts.Map(); @@ -6798,8 +6811,8 @@ var ts; return useNonPollingWatchers ? // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : - // Default to do not use fixed polling interval - { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.UseFsEvents }; + // Default to using fs events + { watchFile: ts.WatchFileKind.UseFsEvents }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -7071,7 +7084,6 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, - defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, inodeWatching: isLinuxOrMacOs, sysLog: sysLog, }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; @@ -9582,6 +9594,10 @@ var ts; Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted: diag(6399, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399", "Project '{0}' is out of date because buildinfo file '{1}' indicates that some of the changes were not emitted"), Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files: diag(6400, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400", "Project '{0}' is up to date but needs to update timestamps of output files that are older than input files"), Project_0_is_out_of_date_because_there_was_error_reading_file_1: diag(6401, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401", "Project '{0}' is out of date because there was error reading file '{1}'"), + Resolving_in_0_mode_with_conditions_1: diag(6402, ts.DiagnosticCategory.Message, "Resolving_in_0_mode_with_conditions_1_6402", "Resolving in {0} mode with conditions {1}."), + Matched_0_condition_1: diag(6403, ts.DiagnosticCategory.Message, "Matched_0_condition_1_6403", "Matched '{0}' condition '{1}'."), + Using_0_subpath_1_with_target_2: diag(6404, ts.DiagnosticCategory.Message, "Using_0_subpath_1_with_target_2_6404", "Using '{0}' subpath '{1}' with target '{2}'."), + Saw_non_matching_condition_0: diag(6405, ts.DiagnosticCategory.Message, "Saw_non_matching_condition_0_6405", "Saw non-matching condition '{0}'."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -9898,6 +9914,8 @@ var ts; Remove_type_from_import_of_0_from_1: diag(90056, ts.DiagnosticCategory.Message, "Remove_type_from_import_of_0_from_1_90056", "Remove 'type' from import of '{0}' from \"{1}\""), Add_import_from_0: diag(90057, ts.DiagnosticCategory.Message, "Add_import_from_0_90057", "Add import from \"{0}\""), Update_import_from_0: diag(90058, ts.DiagnosticCategory.Message, "Update_import_from_0_90058", "Update import from \"{0}\""), + Export_0_from_module_1: diag(90059, ts.DiagnosticCategory.Message, "Export_0_from_module_1_90059", "Export '{0}' from module '{1}'"), + Export_all_referenced_locals: diag(90060, ts.DiagnosticCategory.Message, "Export_all_referenced_locals_90060", "Export all referenced locals"), 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}"), @@ -11355,7 +11373,7 @@ var ts; return -1; } function peekExtendedUnicodeEscape() { - if (languageVersion >= 2 /* ScriptTarget.ES2015 */ && codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { + if (codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { var start_2 = pos; pos += 3; var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); @@ -21658,6 +21676,32 @@ var ts; return parameter.kind === 343 /* SyntaxKind.JSDocParameterTag */ ? (_a = parameter.typeExpression) === null || _a === void 0 ? void 0 : _a.type : parameter.type; } ts.getParameterTypeNode = getParameterTypeNode; + function isTypeDeclaration(node) { + switch (node.kind) { + case 165 /* SyntaxKind.TypeParameter */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: + return true; + case 270 /* SyntaxKind.ImportClause */: + return node.isTypeOnly; + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: + return node.parent.parent.isTypeOnly; + default: + return false; + } + } + ts.isTypeDeclaration = isTypeDeclaration; + function canHaveExportModifier(node) { + return ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) || isTypeDeclaration(node) || (ts.isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node)); + } + ts.canHaveExportModifier = canHaveExportModifier; })(ts || (ts = {})); /* @internal */ var ts; @@ -21666,13 +21710,11 @@ var ts; * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator. */ function createBaseNodeFactory() { - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name return { createBaseSourceFileNode: createBaseSourceFileNode, createBaseIdentifierNode: createBaseIdentifierNode, @@ -23136,7 +23178,7 @@ var ts; return node; } // @api - function createIdentifier(text, typeArguments, originalKeywordKind) { + function createIdentifier(text, typeArguments, originalKeywordKind, hasExtendedUnicodeEscape) { var node = createBaseIdentifier(text, originalKeywordKind); if (typeArguments) { // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations @@ -23145,6 +23187,10 @@ var ts; if (node.originalKeywordKind === 133 /* SyntaxKind.AwaitKeyword */) { node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } + if (hasExtendedUnicodeEscape) { + node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + } return node; } // @api @@ -27600,11 +27646,9 @@ var ts; rawTextScanner.setText("`" + rawText + "`"); break; case 15 /* SyntaxKind.TemplateHead */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("`" + rawText + "${"); break; case 16 /* SyntaxKind.TemplateMiddle */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("}" + rawText + "${"); break; case 17 /* SyntaxKind.TemplateTail */: @@ -27963,7 +28007,6 @@ var ts; return node; } ts.createInputFiles = createInputFiles; - // tslint:disable-next-line variable-name var SourceMapSource; /** * Create an external source map source file reference @@ -28755,6 +28798,8 @@ var ts; // - The verb (`next`, `throw`, or `return` method) to delegate to the expression // of a `yield*`. // - The result of evaluating the verb delegated to the expression of a `yield*`. + // g A temporary variable that holds onto the generator object until the generator + // is started, allowing it to also act as the `suspendedStart` state. // // functions: // verb(n) Creates a bound callback to the `step` function for opcode `n`. @@ -28793,7 +28838,7 @@ var ts; importName: "__generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; // ES Module Helpers ts.createBindingHelper = { @@ -32097,13 +32142,11 @@ var ts; var scanner = ts.createScanner(99 /* ScriptTarget.Latest */, /*skipTrivia*/ true); var disallowInAndDecoratorContext = 4096 /* NodeFlags.DisallowInContext */ | 16384 /* NodeFlags.DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name function countNode(node) { nodeCount++; return node; @@ -33079,8 +33122,9 @@ var ts; // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); var text = internIdentifier(scanner.getTokenValue()); + var hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape(); nextTokenWithoutCheck(); - return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos); + return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind, hasExtendedUnicodeEscape), pos); } if (token() === 80 /* SyntaxKind.PrivateIdentifier */) { parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); @@ -42219,12 +42263,23 @@ var ts; } function writeConfigurations() { // Filter applicable options to place in the file - var categorizedOptions = ts.createMultiMap(); + var categorizedOptions = new ts.Map(); + // Set allowed categories in order + categorizedOptions.set(ts.Diagnostics.Projects, []); + categorizedOptions.set(ts.Diagnostics.Language_and_Environment, []); + categorizedOptions.set(ts.Diagnostics.Modules, []); + categorizedOptions.set(ts.Diagnostics.JavaScript_Support, []); + categorizedOptions.set(ts.Diagnostics.Emit, []); + categorizedOptions.set(ts.Diagnostics.Interop_Constraints, []); + categorizedOptions.set(ts.Diagnostics.Type_Checking, []); + categorizedOptions.set(ts.Diagnostics.Completeness, []); for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { var option = optionDeclarations_1[_i]; - var category = option.category; if (isAllowedOptionForOutput(option)) { - categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + var listForCategory = categorizedOptions.get(option.category); + if (!listForCategory) + categorizedOptions.set(option.category, listForCategory = []); + listForCategory.push(option); } } // Serialize all options and their descriptions @@ -42235,7 +42290,7 @@ var ts; if (entries.length !== 0) { entries.push({ value: "" }); } - entries.push({ value: "/* ".concat(category, " */") }); + entries.push({ value: "/* ".concat(ts.getLocaleSpecificMessage(category), " */") }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -44277,6 +44332,9 @@ var ts; requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; + if (traceEnabled && ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) <= ts.ModuleResolutionKind.NodeNext) { + trace(host, ts.Diagnostics.Resolving_in_0_mode_with_conditions_1, features & NodeResolutionFeatures.EsmMode ? "ESM" : "CJS", conditions.map(function (c) { return "'".concat(c, "'"); }).join(", ")); + } var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { @@ -44866,7 +44924,7 @@ var ts; } if (mainExport) { var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false); - return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false, "."); } } else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) { @@ -44946,7 +45004,7 @@ var ts; var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!ts.endsWith(moduleName, ts.directorySeparator) && moduleName.indexOf("*") === -1 && ts.hasProperty(lookupTable, moduleName)) { var target = lookupTable[moduleName]; - return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName); } var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), comparePatternKeys); for (var _i = 0, expandingKeys_1 = expandingKeys; _i < expandingKeys_1.length; _i++) { @@ -44955,17 +45013,17 @@ var ts; var target = lookupTable[potentialTarget]; var starPos = potentialTarget.indexOf("*"); var subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.endsWith(potentialTarget, "*") && ts.startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length - 1); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.startsWith(moduleName, potentialTarget)) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false, potentialTarget); } } function matchesPatternWithTrailer(target, name) { @@ -44982,7 +45040,7 @@ var ts; */ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) { return loadModuleFromTargetImportOrExport; - function loadModuleFromTargetImportOrExport(target, subpath, pattern) { + function loadModuleFromTargetImportOrExport(target, subpath, pattern, key) { if (typeof target === "string") { if (!pattern && subpath.length > 0 && !ts.endsWith(target, "/")) { if (state.traceEnabled) { @@ -44993,6 +45051,8 @@ var ts; if (!ts.startsWith(target, "./")) { if (isImports && !ts.startsWith(target, "../") && !ts.startsWith(target, "/") && !ts.isRootedDiskPath(target)) { var combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath; + traceIfEnabled(state, ts.Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup); + traceIfEnabled(state, ts.Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/"); var result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, [extensions], redirectedReference); return toSearchResult(result.resolvedModule ? { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId, originalPath: result.resolvedModule.originalPath } : undefined); } @@ -45019,6 +45079,9 @@ var ts; } return toSearchResult(/*value*/ undefined); } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); + } var finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); var inputLink = tryLoadInputFileForPath(finalPath, subpath, ts.combinePaths(scope.packageDirectory, "package.json"), isImports); if (inputLink) @@ -45028,14 +45091,18 @@ var ts; else if (typeof target === "object" && target !== null) { // eslint-disable-line no-null/no-null if (!Array.isArray(target)) { for (var _i = 0, _a = ts.getOwnKeys(target); _i < _a.length; _i++) { - var key = _a[_i]; - if (key === "default" || state.conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(state.conditions, key)) { - var subTarget = target[key]; - var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern); + var condition = _a[_i]; + if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) { + traceIfEnabled(state, ts.Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition); + var subTarget = target[condition]; + var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key); if (result) { return result; } } + else { + traceIfEnabled(state, ts.Diagnostics.Saw_non_matching_condition_0, condition); + } } return undefined; } @@ -45048,7 +45115,7 @@ var ts; } for (var _b = 0, target_2 = target; _b < target_2.length; _b++) { var elem = target_2[_b]; - var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern); + var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern, key); if (result) { return result; } @@ -45464,6 +45531,15 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } + function traceIfEnabled(state, diagnostic) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (state.traceEnabled) { + trace.apply(void 0, __spreadArray([state.host, diagnostic], args, false)); + } + } })(ts || (ts = {})); /* @internal */ var ts; @@ -49055,8 +49131,6 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; - IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var RecursionFlags; (function (RecursionFlags) { @@ -49475,6 +49549,12 @@ var ts; getOptionalType: function () { return optionalType; }, getPromiseType: function () { return getGlobalPromiseType(/*reportErrors*/ false); }, getPromiseLikeType: function () { return getGlobalPromiseLikeType(/*reportErrors*/ false); }, + getAsyncIterableType: function () { + var type = getGlobalAsyncIterableType(/*reportErrors*/ false); + if (type === emptyGenericType) + return undefined; + return type; + }, isSymbolAccessible: isSymbolAccessible, isArrayType: isArrayType, isTupleType: isTupleType, @@ -50312,9 +50392,9 @@ var ts; return symbol; } if (symbol.flags & 2097152 /* SymbolFlags.Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { + var targetFlags = getAllSymbolFlags(symbol); + // `targetFlags` will be `SymbolFlags.All` if an error occurred in alias resolution; this avoids cascading errors + if (targetFlags & meaning) { return symbol; } } @@ -50947,8 +51027,8 @@ var ts; !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && + !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; var suggestedLib = void 0; @@ -51035,7 +51115,7 @@ var ts; } } if (result && errorLocation && meaning & 111551 /* SymbolFlags.Value */ && result.flags & 2097152 /* SymbolFlags.Alias */ && !(result.flags & 111551 /* SymbolFlags.Value */) && !ts.isValidTypeOnlyAliasUseSite(errorLocation)) { - var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); + var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551 /* SymbolFlags.Value */); if (typeOnlyDeclaration) { var message = typeOnlyDeclaration.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type @@ -51198,7 +51278,7 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { + if (meaning & 111551 /* SymbolFlags.Value */) { if (isPrimitiveTypeName(name)) { if (isExtendedByInterface(errorLocation)) { error(errorLocation, ts.Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, ts.unescapeLeadingUnderscores(name)); @@ -51209,7 +51289,8 @@ var ts; return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); - if (symbol && !(symbol.flags & 1024 /* SymbolFlags.NamespaceModule */)) { + var allFlags = symbol && getAllSymbolFlags(symbol); + if (symbol && allFlags !== undefined && !(allFlags & 111551 /* SymbolFlags.Value */)) { var rawName = ts.unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName); @@ -51257,16 +51338,16 @@ var ts; } return false; } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~788968 /* SymbolFlags.Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) { + if (meaning & (111551 /* SymbolFlags.Value */ & ~788968 /* SymbolFlags.Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (788968 /* SymbolFlags.Type */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* SymbolFlags.ValueModule */ | 1024 /* SymbolFlags.NamespaceModule */) & ~788968 /* SymbolFlags.Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1536 /* SymbolFlags.Module */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -51856,6 +51937,52 @@ var ts; } return undefined; } + /** + * Gets combined flags of a `symbol` and all alias targets it resolves to. `resolveAlias` + * is typically recursive over chains of aliases, but stops mid-chain if an alias is merged + * with another exported symbol, e.g. + * ```ts + * // a.ts + * export const a = 0; + * // b.ts + * export { a } from "./a"; + * export type a = number; + * // c.ts + * import { a } from "./b"; + * ``` + * Calling `resolveAlias` on the `a` in c.ts would stop at the merged symbol exported + * from b.ts, even though there is still more alias to resolve. Consequently, if we were + * trying to determine if the `a` in c.ts has a value meaning, looking at the flags on + * the local symbol and on the symbol returned by `resolveAlias` is not enough. + * @returns SymbolFlags.All if `symbol` is an alias that ultimately resolves to `unknown`; + * combined flags of all alias targets otherwise. + */ + function getAllSymbolFlags(symbol) { + var flags = symbol.flags; + var seenSymbols; + while (symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return 67108863 /* SymbolFlags.All */; + } + // Optimizations - try to avoid creating or adding to + // `seenSymbols` if possible + if (target === symbol || (seenSymbols === null || seenSymbols === void 0 ? void 0 : seenSymbols.has(target))) { + break; + } + if (target.flags & 2097152 /* SymbolFlags.Alias */) { + if (seenSymbols) { + seenSymbols.add(target); + } + else { + seenSymbols = new ts.Set([symbol, target]); + } + } + flags |= target.flags; + symbol = target; + } + return flags; + } /** * Marks a symbol as type-only if its declaration is syntactically type-only. * If it is not itself marked type-only, but resolves to a type-only alias @@ -51901,19 +52028,25 @@ var ts; return !!aliasDeclarationLinks.typeOnlyDeclaration; } /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */ - function getTypeOnlyAliasDeclaration(symbol) { + function getTypeOnlyAliasDeclaration(symbol, include) { if (!(symbol.flags & 2097152 /* SymbolFlags.Alias */)) { return undefined; } var links = getSymbolLinks(symbol); - return links.typeOnlyDeclaration || undefined; + if (include === undefined) { + return links.typeOnlyDeclaration || undefined; + } + if (links.typeOnlyDeclaration) { + return getAllSymbolFlags(resolveAlias(links.typeOnlyDeclaration.symbol)) & include ? links.typeOnlyDeclaration : undefined; + } + return undefined; } function markExportAsReferenced(node) { var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol)); + ((getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -51933,8 +52066,7 @@ var ts; // This way a chain of imports can be elided if ultimately the final input is only used in a type // position. if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveSymbol(symbol); - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* SymbolFlags.Value */) { // import foo = checkExpressionCached(node.moduleReference); } @@ -52756,7 +52888,7 @@ var ts; } function symbolIsValue(symbol, includeTypeOnlyMembers) { return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || - symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + symbol.flags & 2097152 /* SymbolFlags.Alias */ && getAllSymbolFlags(symbol) & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -53025,8 +53157,10 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { + var shouldResolveAlias = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)); + symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + var flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + if (flags & meaning) { qualify = true; return true; } @@ -55338,7 +55472,7 @@ var ts; // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it var indices = ts.indicesOf(statements); var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); }); - if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) { + if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return ts.canHaveExportModifier(statements[i]); })) { for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) { var index_1 = associatedIndices_1[_i]; statements[index_1] = addExportModifier(statements[index_1]); @@ -55372,15 +55506,6 @@ var ts; } return statements; } - function canHaveExportModifier(node) { - return ts.isEnumDeclaration(node) || - ts.isVariableStatement(node) || - ts.isFunctionDeclaration(node) || - ts.isClassDeclaration(node) || - (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) || - ts.isInterfaceDeclaration(node) || - isTypeDeclaration(node); - } function addExportModifier(node) { var flags = (ts.getEffectiveModifierFlags(node) | 1 /* ModifierFlags.Export */) & ~2 /* ModifierFlags.Ambient */; return ts.factory.updateModifiers(node, flags); @@ -55627,7 +55752,7 @@ var ts; (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* ModifierFlags.Export */ && enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && - canHaveExportModifier(node)) { + ts.canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* ModifierFlags.Export */; } @@ -55683,7 +55808,7 @@ var ts; return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { - return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* SymbolFlags.Value */); }); + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* SymbolFlags.Value */); }); } function serializeModule(symbol, symbolName, modifierFlags) { var members = getNamespaceMembersForSerialization(symbol); @@ -57903,7 +58028,7 @@ var ts; links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType - : targetSymbol.flags & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) + : getAllSymbolFlags(targetSymbol) & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; @@ -59786,7 +59911,20 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ && getMappedTypeModifiers(type) & 4 /* MappedTypeModifiers.IncludeOptional */); } function isGenericMappedType(type) { - return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + if (ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) { + var constraint = getConstraintTypeFromMappedType(type); + if (isGenericIndexType(constraint)) { + return true; + } + // A mapped type is generic if the 'as' clause references generic types other than the iteration type. + // To determine this, we substitute the constraint type (that we now know isn't generic) for the iteration + // type and check whether the resulting type is generic. + var nameType = getNameTypeFromMappedType(type); + if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) { + return true; + } + } + return false; } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -60256,7 +60394,7 @@ var ts; var indexTypes; var isUnion = containingType.flags & 1048576 /* TypeFlags.Union */; // Flags we want to propagate to the result if they exist in all source symbols - var optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */; + var optionalFlag; var syntheticFlag = 4 /* CheckFlags.SyntheticMethod */; var checkFlags = isUnion ? 0 : 8 /* CheckFlags.Readonly */; var mergedInstantiations = false; @@ -60267,11 +60405,14 @@ var ts; var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop) { - if (isUnion) { - optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); - } - else { - optionalFlag &= prop.flags; + if (prop.flags & 106500 /* SymbolFlags.ClassMember */) { + optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : (optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */); + if (isUnion) { + optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); + } + else { + optionalFlag &= prop.flags; + } } if (!singleProp) { singleProp = prop; @@ -60390,7 +60531,7 @@ var ts; propTypes.push(type); } ts.addRange(propTypes, indexTypes); - var result = createSymbol(4 /* SymbolFlags.Property */ | optionalFlag, name, syntheticFlag | checkFlags); + var result = createSymbol(4 /* SymbolFlags.Property */ | (optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : 0), name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && firstValueDeclaration) { result.valueDeclaration = firstValueDeclaration; @@ -63103,8 +63244,14 @@ var ts; return getStringLiteralType(text); } newTexts.push(text); - if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { - return stringType; + if (ts.every(newTexts, function (t) { return t === ""; })) { + if (ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { + return stringType; + } + // Normalize `${Mapping}` into Mapping + if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) { + return newTypes[0]; + } } var id = "".concat(getTypeListId(newTypes), "|").concat(ts.map(newTexts, function (t) { return t.length; }).join(","), "|").concat(newTexts.join("")); var type = templateLiteralTypes.get(id); @@ -63163,12 +63310,14 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - // Mapping> === Mapping - type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : - isGenericIndexType(type) || isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, isPatternLiteralPlaceholderType(type) && !(type.flags & 268435456 /* TypeFlags.StringMapping */) ? getTemplateLiteralType(["", ""], [type]) : type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : - type; + type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : + type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : + // Mapping> === Mapping + type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : + type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : + // This handles Mapping<`${number}`> and Mapping<`${bigint}`> + isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : + type; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -63333,7 +63482,18 @@ var ts; return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; } errorIfWritingToReadonlyIndex(indexInfo); - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; + // When accessing an enum object with its own type, + // e.g. E[E.A] for enum E { A }, undefined shouldn't + // be included in the result type + if ((accessFlags & 1 /* AccessFlags.IncludeUndefined */) && + !(objectType.symbol && + objectType.symbol.flags & (256 /* SymbolFlags.RegularEnum */ | 128 /* SymbolFlags.ConstEnum */) && + (indexType.symbol && + indexType.flags & 1024 /* TypeFlags.EnumLiteral */ && + getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + return getUnionType([indexInfo.type, undefinedType]); + } + return indexInfo.type; } if (indexType.flags & 131072 /* TypeFlags.Never */) { return neverType; @@ -63436,10 +63596,11 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || isPatternLiteralType(type); } function isPatternLiteralType(type) { - return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); + return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType) || + !!(type.flags & 268435456 /* TypeFlags.StringMapping */) && isPatternLiteralPlaceholderType(type.type); } function isGenericType(type) { return !!getGenericObjectFlags(type); @@ -63718,18 +63879,23 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_20 = function () { + // We loop here for an immediately nested conditional type in the false position, effectively treating + // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for + // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of + // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive + // cases we increment the tail recursion counter and stop after 1000 iterations. + while (true) { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; - return "break"; + break; } var isUnwrapped = isTypicalNondistributiveConditional(root); var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { - return { value: wildcardType }; + return wildcardType; } var combinedMapper = void 0; if (root.inferTypeParameters) { @@ -63762,11 +63928,7 @@ var ts; } } } - // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type - // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to - // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint - // so in those cases we refain from performing inference and retain the uninfered type parameter - if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -63798,14 +63960,14 @@ var ts; var newRoot = falseType_1.root; if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) { root = newRoot; - return "continue"; + continue; } if (canTailRecurse(falseType_1, mapper)) { - return "continue"; + continue; } } result = instantiateType(falseType_1, mapper); - return "break"; + break; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -63816,10 +63978,10 @@ var ts; var trueType_1 = getTypeFromTypeNode(root.node.trueType); var trueMapper = combinedMapper || mapper; if (canTailRecurse(trueType_1, trueMapper)) { - return "continue"; + continue; } result = instantiateType(trueType_1, trueMapper); - return "break"; + break; } } // Return a deferred type for a check that is neither definitely true nor definitely false @@ -63831,19 +63993,7 @@ var ts; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 - return "break"; - }; - // We loop here for an immediately nested conditional type in the false position, effectively treating - // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for - // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of - // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive - // cases we increment the tail recursion counter and stop after 1000 iterations. - while (true) { - var state_6 = _loop_20(); - if (typeof state_6 === "object") - return state_6.value; - if (state_6 === "break") - break; + break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; // We tail-recurse for generic conditional types that (a) have not already been evaluated and cached, and @@ -66297,7 +66447,7 @@ var ts; return 0 /* Ternary.False */; } } - var isPerformingCommonPropertyChecks = (relation !== comparableRelation || !(source.flags & 1048576 /* TypeFlags.Union */) && isLiteralType(source)) && + var isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source)) && !(intersectionState & 2 /* IntersectionState.Target */) && source.flags & (131068 /* TypeFlags.Primitive */ | 524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && source !== globalObjectType && target.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && isWeakType(target) && @@ -66325,27 +66475,6 @@ var ts; var result_7 = skipCaching ? unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) : recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags); - // For certain combinations involving intersections and optional, excess, or mismatched properties we need - // an extra property check where the intersection is viewed as a single object. The following are motivating - // examples that all should be errors, but aren't without this extra property check: - // - // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property - // - // declare let wrong: { a: { y: string } }; - // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type - // - // function foo(x: { a?: string }, y: T & { a: boolean }) { - // x = y; // Mismatched property in source intersection - // } - // - // We suppress recursive intersection property checks because they can generate lots of work when relating - // recursive intersections that are structurally similar but not exactly identical. See #37854. - if (result_7 && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { - inPropertyCheck = true; - result_7 &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* IntersectionState.PropertyCheck */, recursionFlags); - inPropertyCheck = false; - } if (result_7) { return result_7; } @@ -66457,7 +66586,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_21 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -66520,9 +66649,9 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_7 = _loop_21(prop); - if (typeof state_7 === "object") - return state_7.value; + var state_6 = _loop_20(prop); + if (typeof state_6 === "object") + return state_6.value; } return false; } @@ -66743,8 +66872,7 @@ var ts; if (overflow) { return 0 /* Ternary.False */; } - var keyIntersectionState = intersectionState | (inPropertyCheck ? 8 /* IntersectionState.InPropertyCheck */ : 0); - var id = getRelationKey(source, target, keyIntersectionState, relation, /*ingnoreConstraints*/ false); + var id = getRelationKey(source, target, intersectionState, relation, /*ingnoreConstraints*/ false); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* RelationComparisonResult.Failed */ && !(entry & 4 /* RelationComparisonResult.Reported */)) { @@ -66774,7 +66902,7 @@ var ts; // A key that starts with "*" is an indication that we have type references that reference constrained // type parameters. For such keys we also check against the key we would have gotten if all type parameters // were unconstrained. - var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, keyIntersectionState, relation, /*ignoreConstraints*/ true) : undefined; + var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, intersectionState, relation, /*ignoreConstraints*/ true) : undefined; for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { @@ -66861,7 +66989,7 @@ var ts; function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { var saveErrorInfo = captureErrorCalculationState(); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo); - if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + if (relation !== identityRelation) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -66875,10 +67003,33 @@ var ts; // needs to have its constraint hoisted into an intersection with said type parameter, this way // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` - var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); - if (constraint && !(constraint.flags & 131072 /* TypeFlags.Never */) && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself - // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this - result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); + if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself + // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this + result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + } + } + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && !isGenericObjectType(target) && source.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) || + isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { + inPropertyCheck = true; + result &= propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); + inPropertyCheck = false; } } if (result) { @@ -66887,9 +67038,6 @@ var ts; return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo) { - if (intersectionState & 4 /* IntersectionState.PropertyCheck */) { - return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); - } var result; var originalErrorInfo; var varianceCheckFailed = false; @@ -66990,7 +67138,7 @@ var ts; // with another type parameter unless one extends the other. (Remember: comparability is mostly bidirectional!) var constraint = getConstraintOfTypeParameter(source); if (constraint && hasNonCircularBaseConstraint(source)) { - while (constraint && constraint.flags & 262144 /* TypeFlags.TypeParameter */) { + while (constraint && someType(constraint, function (c) { return !!(c.flags & 262144 /* TypeFlags.TypeParameter */); })) { if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { return result; } @@ -67513,11 +67661,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_22 = function (combination) { + var _loop_21 = function (combination) { var hasMatch = false; outer: for (var _c = 0, _d = target.types; _c < _d.length; _c++) { var type = _d[_c]; - var _loop_23 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -67533,8 +67681,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_9 = _loop_23(i); - switch (state_9) { + var state_8 = _loop_22(i); + switch (state_8) { case "continue-outer": continue outer; } } @@ -67547,9 +67695,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_8 = _loop_22(combination); - if (typeof state_8 === "object") - return state_8.value; + var state_7 = _loop_21(combination); + if (typeof state_7 === "object") + return state_7.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* Ternary.True */; @@ -67646,7 +67794,7 @@ var ts; return 0 /* Ternary.False */; } // When checking for comparability, be more lenient with optional properties. - if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && targetProp.flags & 106500 /* SymbolFlags.ClassMember */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -68254,7 +68402,7 @@ var ts; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); links.variances = ts.emptyArray; var variances = []; - var _loop_24 = function (tp) { + var _loop_23 = function (tp) { var modifiers = getVarianceModifiers(tp); var variance = modifiers & 65536 /* ModifierFlags.Out */ ? modifiers & 32768 /* ModifierFlags.In */ ? 0 /* VarianceFlags.Invariant */ : 1 /* VarianceFlags.Covariant */ : @@ -68292,7 +68440,7 @@ var ts; }; for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var tp = typeParameters_2[_i]; - _loop_24(tp); + _loop_23(tp); } links.variances = variances; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); @@ -68746,8 +68894,7 @@ var ts; return !!(type.flags & 109440 /* TypeFlags.Unit */); } function isUnitLikeType(type) { - return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.some(type.types, isUnitType) : - !!(type.flags & 109440 /* TypeFlags.Unit */); + return isUnitType(getBaseConstraintOrType(type)); } function extractUnitType(type) { return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.find(type.types, isUnitType) || type : type; @@ -69626,7 +69773,7 @@ var ts; && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); } function isMemberOfStringMapping(source, target) { - if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + if (target.flags & (4 /* TypeFlags.String */ | 1 /* TypeFlags.Any */)) { return true; } if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { @@ -70250,7 +70397,7 @@ var ts; // upon instantiation, would collapse all the placeholders to just 'string', and an assignment check might // succeed. That would be a pointless and confusing outcome. if (matches || ts.every(target.texts, function (s) { return s.length === 0; })) { - var _loop_25 = function (i) { + var _loop_24 = function (i) { var source_1 = matches ? matches[i] : neverType; var target_3 = types[i]; // If we are inferring from a string literal type to a type variable whose constraint includes one of the @@ -70300,7 +70447,7 @@ var ts; inferFromTypes(source_1, target_3); }; for (var i = 0; i < types.length; i++) { - _loop_25(i); + _loop_24(i); } } } @@ -70752,7 +70899,7 @@ var ts; } if (ts.isEntityNameExpression(node.argumentExpression)) { var symbol = resolveEntityName(node.argumentExpression, 111551 /* SymbolFlags.Value */, /*ignoreErrors*/ true); - if (!symbol || !isConstVariable(symbol)) + if (!symbol || !(isConstVariable(symbol) || (symbol.flags & 8 /* SymbolFlags.EnumMember */))) return undefined; var declaration = symbol.valueDeclaration; if (declaration === undefined) @@ -70766,7 +70913,12 @@ var ts; } if (ts.hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node.argumentExpression)) { var initializer = ts.getEffectiveInitializer(declaration); - return initializer && tryGetNameFromType(getTypeOfExpression(initializer)); + if (initializer) { + return tryGetNameFromType(getTypeOfExpression(initializer)); + } + if (ts.isEnumMember(declaration)) { + return ts.getTextOfPropertyName(declaration.name); + } } } return undefined; @@ -70824,7 +70976,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_26 = function (type) { + var _loop_25 = function (type) { if (type.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */ | 58982400 /* TypeFlags.InstantiableNonPrimitive */)) { var discriminant = getTypeOfPropertyOfType(type, name); if (discriminant) { @@ -70850,9 +71002,9 @@ var ts; }; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var type = types_15[_i]; - var state_10 = _loop_26(type); - if (typeof state_10 === "object") - return state_10.value; + var state_9 = _loop_25(type); + if (typeof state_9 === "object") + return state_9.value; } return count >= 10 && count * 2 >= types.length ? map : undefined; } @@ -71449,6 +71601,7 @@ var ts; ts.isInJSFile(node) && ts.hasInitializer(node) && node.initializer && ts.isFunctionExpressionOrArrowFunction(node.initializer) && ts.getEffectiveReturnTypeNode(node.initializer)); } function getExplicitTypeOfSymbol(symbol, diagnostic) { + symbol = resolveSymbol(symbol); if (symbol.flags & (16 /* SymbolFlags.Function */ | 8192 /* SymbolFlags.Method */ | 32 /* SymbolFlags.Class */ | 512 /* SymbolFlags.ValueModule */)) { return getTypeOfSymbol(symbol); } @@ -71487,7 +71640,7 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); - return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol, diagnostic); + return getExplicitTypeOfSymbol(symbol, diagnostic); case 108 /* SyntaxKind.ThisKeyword */: return getExplicitThisType(node); case 106 /* SyntaxKind.SuperKeyword */: @@ -71974,7 +72127,7 @@ var ts; type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (expr.kind === 218 /* SyntaxKind.TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { - type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { if (strictNullChecks) { @@ -72255,7 +72408,7 @@ var ts; !!(prop.flags & 16777216 /* SymbolFlags.Optional */) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue; } - function narrowByInKeyword(type, nameType, assumeTrue) { + function narrowTypeByInKeyword(type, nameType, assumeTrue) { var name = getPropertyNameFromType(nameType); var isKnownProperty = someType(type, function (t) { return isTypePresencePossible(t, name, /*assumeTrue*/ true); }); if (isKnownProperty) { @@ -72336,7 +72489,7 @@ var ts; return getTypeWithFacts(type, assumeTrue ? 524288 /* TypeFacts.NEUndefined */ : 65536 /* TypeFacts.EQUndefined */); } if (isMatchingReference(reference, target)) { - return narrowByInKeyword(type, leftType, assumeTrue); + return narrowTypeByInKeyword(type, leftType, assumeTrue); } } break; @@ -72525,7 +72678,7 @@ var ts; neverType; }); } - function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + function narrowTypeBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!witnesses) { return type; @@ -72913,15 +73066,15 @@ var ts; }); } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { var target = resolveAlias(symbol); - if (target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */)) { // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled // (because the const enum value will not be inlined), or if (2) the alias is an export // of a const enum declaration that will be preserved. if (compilerOptions.isolatedModules || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || - !isConstEnumOrConstEnumOnlyModule(target)) { + !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -73149,7 +73302,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 16384 /* TypeFlags.Void */)) !== 0 || isInTypeQuery(node) || node.parent.kind === 278 /* SyntaxKind.ExportSpecifier */) || node.parent.kind === 232 /* SyntaxKind.NonNullExpression */ || @@ -73178,6 +73331,12 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function isSameScopedBindingElement(node, declaration) { + if (ts.isBindingElement(declaration)) { + var bindingElement = ts.findAncestor(node, ts.isBindingElement); + return bindingElement && ts.getRootDeclaration(bindingElement) === ts.getRootDeclaration(declaration); + } + } function shouldMarkIdentifierAliasReferenced(node) { var _a; var parent = node.parent; @@ -73519,12 +73678,17 @@ var ts; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; + var inAsyncFunction = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { while (container && container.kind === 216 /* SyntaxKind.ArrowFunction */) { + if (ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ScriptTarget.ES2015 */; } + if (container && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; @@ -73630,12 +73794,12 @@ var ts; // as a call expression cannot be used as the target of a destructuring assignment while a property access can. // // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. - if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) { + if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && inAsyncFunction) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */; + getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */; } else { - getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.AsyncMethodWithSuper */; + getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */; } } if (needToCaptureLexicalThis) { @@ -74331,9 +74495,10 @@ var ts; function instantiateContextualType(contextualType, node, contextFlags) { if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* TypeFlags.Instantiable */)) { var inferenceContext = getInferenceContext(node); - // If no inferences have been made, nothing is gained from instantiating as type parameters - // would just be replaced with their defaults similar to the apparent type. - if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + // If no inferences have been made, and none of the type parameters for which we are inferring + // specify default types, nothing is gained from instantiating as type parameters would just be + // replaced with their constraints similar to the apparent type. + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) { // For contextual signatures we incorporate all inferences made so far, e.g. from return // types as well as arguments to the left in a function call. return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); @@ -77307,7 +77472,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_27 = function (i) { + var _loop_26 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. var spreadType = arg.kind === 227 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -77324,7 +77489,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_27(i); + _loop_26(i); } return effectiveArgs_1; } @@ -77653,7 +77818,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_28 = function (c) { + var _loop_27 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* CheckMode.Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -77671,7 +77836,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_28(c); + _loop_27(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -77829,7 +77994,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_29 = function (i) { + var _loop_28 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -77837,7 +78002,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_29(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -78807,7 +78972,7 @@ var ts; if (symbol && symbol.flags & 2097152 /* SymbolFlags.Alias */) { symbol = resolveAlias(symbol); } - return !!(symbol && (symbol.flags & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); + return !!(symbol && (getAllSymbolFlags(symbol) & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); } return false; } @@ -79469,7 +79634,17 @@ var ts; } function isExhaustiveSwitchStatement(node) { var links = getNodeLinks(node); - return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); + if (links.isExhaustive === undefined) { + links.isExhaustive = 0; // Indicate resolution is in process + var exhaustive = computeExhaustiveSwitchStatement(node); + if (links.isExhaustive === 0) { + links.isExhaustive = exhaustive; + } + } + else if (links.isExhaustive === 0) { + links.isExhaustive = false; // Resolve circularity to false + } + return links.isExhaustive; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 218 /* SyntaxKind.TypeOfExpression */) { @@ -79477,7 +79652,7 @@ var ts; if (!witnesses) { return false; } - var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(node.expression.expression)); + var operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression)); // Get the not-equal flags for all handled cases. var notEqualFacts_2 = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); if (operandConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */) { @@ -79487,7 +79662,7 @@ var ts; // A missing not-equal flag indicates that the type wasn't handled by some case. return !someType(operandConstraint, function (t) { return (getTypeFacts(t) & notEqualFacts_2) === notEqualFacts_2; }); } - var type = getTypeOfExpression(node.expression); + var type = checkExpressionCached(node.expression); if (!isLiteralType(type)) { return false; } @@ -81181,6 +81356,9 @@ var ts; function hasInferenceCandidates(info) { return !!(info.candidates || info.contraCandidates); } + function hasInferenceCandidatesOrDefault(info) { + return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter)); + } function hasOverlappingInferences(a, b) { for (var i = 0; i < a.length; i++) { if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) { @@ -81882,7 +82060,7 @@ var ts; var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var indexSignatureMap_1 = new ts.Map(); - var _loop_30 = function (declaration) { + var _loop_29 = function (declaration) { if (declaration.parameters.length === 1 && declaration.parameters[0].type) { forEachType(getTypeFromTypeNode(declaration.parameters[0].type), function (type) { var entry = indexSignatureMap_1.get(getTypeId(type)); @@ -81897,7 +82075,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_30(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -82174,7 +82352,7 @@ var ts; } var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { - if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { + if (ts.some(symbol.declarations, function (d) { return ts.isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* TypeFlags.Enum */ && symbol.flags & 8 /* SymbolFlags.EnumMember */) { @@ -82777,7 +82955,7 @@ var ts; return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; } // primitives with a `{ then() }` won't be unwrapped/adopted. - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217 @@ -82844,7 +83022,7 @@ var ts; * Determines whether a type is an object with a callable `then` member. */ function isThenableType(type) { - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { // primitive types cannot be considered "thenable" since they are not objects. return false; } @@ -82878,7 +83056,7 @@ var ts; // We only need `Awaited` if `T` is a type variable that has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`, // or is promise-like. if (baseConstraint ? - baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint) : + baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { return true; } @@ -83552,7 +83730,7 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + var message = ts.isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(declaration, 0 /* UnusedKind.Local */, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { @@ -84982,7 +85160,16 @@ var ts; var message = allowAsyncIterables ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; - return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + var suggestAwait = + // for (const x of Promise<...>) or [...Promise<...>] + !!getAwaitedTypeOfPromise(type) + // for (const x of AsyncIterable<...>) + || (!allowAsyncIterables && + ts.isForOfStatement(errorNode.parent) && + errorNode.parent.expression === errorNode && + getGlobalAsyncIterableType(/** reportErrors */ false) !== emptyGenericType && + isTypeAssignableTo(type, getGlobalAsyncIterableType(/** reportErrors */ false))); + return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. @@ -85497,7 +85684,7 @@ var ts; var propDeclaration = declaration && declaration.kind === 223 /* SyntaxKind.BinaryExpression */ || name && name.kind === 164 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_31 = function (info) { + var _loop_30 = function (info) { var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; // We check only when (a) the property is declared in the containing type, or (b) the applicable index signature is declared // in the containing type, or (c) the containing type is an interface and no base interface contains both the property and @@ -85514,7 +85701,7 @@ var ts; }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_31(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -85522,7 +85709,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 261 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_32 = function (info) { + var _loop_31 = function (info) { if (info === checkInfo) return "continue"; var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; @@ -85537,7 +85724,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_32(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -85592,7 +85779,7 @@ var ts; } else { ts.forEach(jsdocParameters, function (_a, index) { - var name = _a.name; + var name = _a.name, isNameFirst = _a.isNameFirst; if (excludedParameters.has(index) || ts.isIdentifier(name) && parameters.has(name.escapedText)) { return; } @@ -85602,7 +85789,9 @@ var ts; } } else { - errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + if (!isNameFirst) { + errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + } } }); } @@ -85857,7 +86046,7 @@ var ts; 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 _loop_33 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -85874,7 +86063,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_33(member); + _loop_32(member); } } /** @@ -85962,7 +86151,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_34 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -85981,7 +86170,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_34(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -86052,7 +86241,7 @@ var ts; var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - var _loop_35 = function (baseProperty) { + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { return "continue"; @@ -86162,8 +86351,8 @@ var ts; }; basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { var baseProperty = baseProperties_1[_i]; - var state_11 = _loop_35(baseProperty); - switch (state_11) { + var state_10 = _loop_34(baseProperty); + switch (state_10) { case "continue-basePropertyCheck": continue basePropertyCheck; } } @@ -86682,12 +86871,11 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { - var _a; switch (node.kind) { case 240 /* SyntaxKind.VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { - var decl = _b[_i]; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; @@ -86703,8 +86891,8 @@ var ts; case 257 /* SyntaxKind.VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { - var el = _d[_c]; + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -86720,18 +86908,6 @@ var ts; if (isGlobalAugmentation) { return; } - var symbol = getSymbolOfNode(node); - if (symbol) { - // module augmentations cannot introduce new names on the top level scope of the module - // this is done it two steps - // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error - // 2. main check - report error if value declaration of the parent symbol is module augmentation) - var reportError = !(symbol.flags & 33554432 /* SymbolFlags.Transient */); - if (!reportError) { - // symbol should not originate in augmentation - reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } break; } } @@ -86833,10 +87009,11 @@ var ts; } return; } + var targetFlags = getAllSymbolFlags(target); var excludedMeanings = (symbol.flags & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */) ? 111551 /* SymbolFlags.Value */ : 0) | (symbol.flags & 788968 /* SymbolFlags.Type */ ? 788968 /* SymbolFlags.Type */ : 0) | (symbol.flags & 1920 /* SymbolFlags.Namespace */ ? 1920 /* SymbolFlags.Namespace */ : 0); - if (target.flags & excludedMeanings) { + if (targetFlags & excludedMeanings) { var message = node.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; @@ -86846,7 +87023,7 @@ var ts; && !ts.isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 16777216 /* NodeFlags.Ambient */)) { var typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol); - var isType = !(target.flags & 111551 /* SymbolFlags.Value */); + var isType = !(targetFlags & 111551 /* SymbolFlags.Value */); if (isType || typeOnlyAlias) { switch (node.kind) { case 270 /* SyntaxKind.ImportClause */: @@ -87006,14 +87183,15 @@ var ts; if (node.moduleReference.kind !== 280 /* SyntaxKind.ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 111551 /* SymbolFlags.Value */) { + var targetFlags = getAllSymbolFlags(target); + if (targetFlags & 111551 /* SymbolFlags.Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* SymbolFlags.Value */ | 1920 /* SymbolFlags.Namespace */).flags & 1920 /* SymbolFlags.Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 788968 /* SymbolFlags.Type */) { + if (targetFlags & 788968 /* SymbolFlags.Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -87152,7 +87330,7 @@ var ts; markExportAsReferenced(node); } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); - if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (!target || getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); } } @@ -87199,7 +87377,7 @@ var ts; markAliasReferenced(sym, id); // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`) var target = sym.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(sym) : sym; - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { // However if it is a value, we need to check it's being used correctly checkExpressionCached(node.expression); } @@ -87871,29 +88049,9 @@ var ts; } function isTypeDeclarationName(name) { return name.kind === 79 /* SyntaxKind.Identifier */ && - isTypeDeclaration(name.parent) && + ts.isTypeDeclaration(name.parent) && ts.getNameOfDeclaration(name.parent) === name; } - function isTypeDeclaration(node) { - switch (node.kind) { - case 165 /* SyntaxKind.TypeParameter */: - case 260 /* SyntaxKind.ClassDeclaration */: - case 261 /* SyntaxKind.InterfaceDeclaration */: - case 262 /* SyntaxKind.TypeAliasDeclaration */: - case 263 /* SyntaxKind.EnumDeclaration */: - case 348 /* SyntaxKind.JSDocTypedefTag */: - case 341 /* SyntaxKind.JSDocCallbackTag */: - case 342 /* SyntaxKind.JSDocEnumTag */: - return true; - case 270 /* SyntaxKind.ImportClause */: - return node.isTypeOnly; - case 273 /* SyntaxKind.ImportSpecifier */: - case 278 /* SyntaxKind.ExportSpecifier */: - return node.parent.parent.isTypeOnly; - default: - return false; - } - } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { while (node.parent.kind === 163 /* SyntaxKind.QualifiedName */) { @@ -88326,7 +88484,7 @@ var ts; var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } - if (isTypeDeclaration(node)) { + if (ts.isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration var symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); @@ -88521,7 +88679,7 @@ var ts; return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 111551 /* SymbolFlags.Value */); + return s && !!(getAllSymbolFlags(s) & 111551 /* SymbolFlags.Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -88574,7 +88732,7 @@ var ts; var symbol = getReferencedValueOrAliasSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -88662,7 +88820,7 @@ var ts; case 273 /* SyntaxKind.ImportSpecifier */: case 278 /* SyntaxKind.ExportSpecifier */: var symbol = getSymbolOfNode(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); + return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */); case 275 /* SyntaxKind.ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || @@ -88684,6 +88842,7 @@ var ts; return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); } function isAliasResolvedToValue(symbol) { + var _a; if (!symbol) { return false; } @@ -88693,7 +88852,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 111551 /* SymbolFlags.Value */) && + return !!(((_a = getAllSymbolFlags(target)) !== null && _a !== void 0 ? _a : -1) & 111551 /* SymbolFlags.Value */) && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -88708,7 +88867,7 @@ var ts; } var target = getSymbolLinks(symbol).aliasTarget; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* ModifierFlags.Export */ && - target.flags & 111551 /* SymbolFlags.Value */ && + getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */ && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; @@ -98362,8 +98521,11 @@ var ts; } return ts.visitEachChild(node, visitor, context); case 174 /* SyntaxKind.GetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitGetAccessorDeclaration, node); case 175 /* SyntaxKind.SetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitSetAccessorDeclaration, node); case 173 /* SyntaxKind.Constructor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitConstructorDeclaration, node); case 260 /* SyntaxKind.ClassDeclaration */: case 228 /* SyntaxKind.ClassExpression */: return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitDefault, node); @@ -98464,6 +98626,9 @@ var ts; return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression( /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); + } /** * Visits a MethodDeclaration node. * @@ -98478,7 +98643,14 @@ var ts; /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) - : ts.visitFunctionBody(node.body, visitor, context)); + : transformMethodBody(node)); + } + function visitGetAccessorDeclaration(node) { + return factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformMethodBody(node)); + } + function visitSetAccessorDeclaration(node) { + return factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); } /** * Visits a FunctionDeclaration node. @@ -98592,6 +98764,42 @@ var ts; } return false; } + function transformMethodBody(node) { + ts.Debug.assertIsDefined(node.body); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = new ts.Set(); + hasSuperElementAccess = false; + var updated = ts.visitFunctionBody(node.body, visitor, context); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var originalMethod = ts.getOriginalNode(node, ts.isFunctionLikeDeclaration); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && + resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) && + (ts.getFunctionFlags(originalMethod) & 3 /* FunctionFlags.AsyncGenerator */) !== 3 /* FunctionFlags.AsyncGenerator */; + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + if (capturedSuperProperties.size) { + var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + var statements = updated.statements.slice(); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + updated = factory.updateBlock(updated, statements); + } + if (hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { + ts.addEmitHelper(updated, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { + ts.addEmitHelper(updated, ts.asyncSuperHelper); + } + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return updated; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -98624,7 +98832,7 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { @@ -98637,10 +98845,10 @@ var ts; ts.setTextRange(block, node.body); if (emitSuperHelpers && hasSuperElementAccess) { // Emit helpers for super element access expressions (`super[x]`). - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -98712,7 +98920,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ES2017SubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -98789,7 +98997,7 @@ var ts; || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -98804,7 +99012,7 @@ var ts; function createSuperAccessVariableStatement(factory, resolver, node, names) { // Create a variable declaration with a getter/setter (if binding) definition for each name: // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); - var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) !== 0; + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) !== 0; var accessors = []; names.forEach(function (_, key) { var name = ts.unescapeLeadingUnderscores(key); @@ -99297,11 +99505,22 @@ var ts; } return node; } - function convertForOfStatementHead(node, boundValue) { - var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue); + function convertForOfStatementHead(node, boundValue, nonUserCode) { + var value = factory.createTempVariable(hoistVariableDeclaration); + var iteratorValueExpression = factory.createAssignment(value, boundValue); + var iteratorValueStatement = factory.createExpressionStatement(iteratorValueExpression); + ts.setSourceMapRange(iteratorValueStatement, node.expression); + var exitNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createFalse()); + var exitNonUserCodeStatement = factory.createExpressionStatement(exitNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var enterNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createTrue()); + var enterNonUserCodeStatement = factory.createExpressionStatement(enterNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var statements = []; + var binding = ts.createForOfBindingStatement(factory, node.initializer, value); + statements.push(ts.visitNode(binding, visitor, ts.isStatement)); var bodyLocation; var statementsLocation; - var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); @@ -99311,8 +99530,16 @@ var ts; else { statements.push(statement); } - return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), + var body = ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* EmitFlags.NoSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */); + return factory.createBlock([ + iteratorValueStatement, + exitNonUserCodeStatement, + factory.createTryStatement(body, + /*catchClause*/ undefined, factory.createBlock([ + enterNonUserCodeStatement + ])) + ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ @@ -99323,6 +99550,8 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined); + var nonUserCode = factory.createTempVariable(/*recordTempVariable*/ undefined); + var done = factory.createTempVariable(hoistVariableDeclaration); var errorRecord = factory.createUniqueName("e"); var catchVariable = factory.getGeneratedNameForNode(errorRecord); var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined); @@ -99339,12 +99568,17 @@ var ts; callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement( /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([ + factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()), ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression), factory.createVariableDeclaration(result) ]), node.expression), 2097152 /* EmitFlags.NoHoisting */), - /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), + /*condition*/ factory.inlineExpressions([ + factory.createAssignment(result, createDownlevelAwait(callNext)), + factory.createAssignment(done, getDone), + factory.createLogicalNot(done) + ]), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, getValue)), + /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode)), /*location*/ node), 256 /* EmitFlags.NoTokenTrailingSourceMaps */); ts.setOriginalNode(forStatement, node); return factory.createTryStatement(factory.createBlock([ @@ -99356,7 +99590,7 @@ var ts; ]), 1 /* EmitFlags.SingleLine */)), factory.createBlock([ factory.createTryStatement( /*tryBlock*/ factory.createBlock([ - ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(getDone)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) + ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(factory.createLogicalNot(nonUserCode), factory.createLogicalNot(done)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([ @@ -99512,7 +99746,7 @@ var ts; /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HierarchyFacts.HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); @@ -99523,10 +99757,10 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = factory.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -99655,7 +99889,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ESNextSubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -99732,7 +99966,7 @@ var ts; || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -101201,11 +101435,13 @@ var ts; return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); } function visitIdentifier(node) { - if (!convertedLoopState) { - return node; + if (convertedLoopState) { + if (resolver.isArgumentsLocalBinding(node)) { + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + } } - if (resolver.isArgumentsLocalBinding(node)) { - return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + if (node.hasExtendedUnicodeEscape) { + return ts.setOriginalNode(ts.setTextRange(factory.createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText)), node), node); } return node; } @@ -105352,7 +105588,6 @@ var ts; return node; } function transformAndEmitForInStatement(node) { - // TODO(rbuckton): Source map locations if (containsYield(node)) { // [source] // for (var p in o) { @@ -105360,34 +105595,41 @@ var ts; // } // // [intermediate] - // .local _a, _b, _i - // _a = []; - // for (_b in o) _a.push(_b); + // .local _b, _a, _c, _i + // _b = []; + // _a = o; + // for (_c in _a) _b.push(_c); // _i = 0; // .loop incrementLabel, endLoopLabel // .mark conditionLabel - // .brfalse endLoopLabel, (_i < _a.length) - // p = _a[_i]; + // .brfalse endLoopLabel, (_i < _b.length) + // _c = _b[_i]; + // .brfalse incrementLabel, (_c in _a) + // p = _c; // /*body*/ // .mark incrementLabel - // _b++; + // _c++; // .br conditionLabel // .endloop // .mark endLoopLabel - var keysArray = declareLocal(); // _a - var key = declareLocal(); // _b + var obj = declareLocal(); // _a + var keysArray = declareLocal(); // _b + var key = declareLocal(); // _c var keysIndex = factory.createLoopVariable(); // _i var initializer = node.initializer; hoistVariableDeclaration(keysIndex); + emitAssignment(obj, ts.visitNode(node.expression, visitor, ts.isExpression)); emitAssignment(keysArray, factory.createArrayLiteralExpression()); - emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), + emitStatement(factory.createForInStatement(key, obj, factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), /*typeArguments*/ undefined, [key])))); emitAssignment(keysIndex, factory.createNumericLiteral(0)); var conditionLabel = defineLabel(); var incrementLabel = defineLabel(); - var endLabel = beginLoopBlock(incrementLabel); + var endLoopLabel = beginLoopBlock(incrementLabel); markLabel(conditionLabel); - emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitBreakWhenFalse(endLoopLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitAssignment(key, factory.createElementAccessExpression(keysArray, keysIndex)); + emitBreakWhenFalse(incrementLabel, factory.createBinaryExpression(key, 101 /* SyntaxKind.InKeyword */, obj)); var variable = void 0; if (ts.isVariableDeclarationList(initializer)) { for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { @@ -105400,7 +105642,7 @@ var ts; variable = ts.visitNode(initializer, visitor, ts.isExpression); ts.Debug.assert(ts.isLeftHandSideExpression(variable)); } - emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex)); + emitAssignment(variable, key); transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex))); @@ -107241,7 +107483,7 @@ var ts; return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return createImportCallExpressionCommonJS(argument, containsLexicalThis); + return createImportCallExpressionCommonJS(argument); } } function createImportCallExpressionUMD(arg, containsLexicalThis) { @@ -107264,7 +107506,7 @@ var ts; return factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(arg), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); } @@ -107273,7 +107515,7 @@ var ts; return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, /* isInlineable */ true), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); } @@ -107323,14 +107565,20 @@ var ts; } return promise; } - function createImportCallExpressionCommonJS(arg, containsLexicalThis) { - // import("./blah") + function createImportCallExpressionCommonJS(arg, isInlineable) { + // import(x) // emit as - // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // var _a; + // (_a = x, Promise.resolve().then(() => require(_a)) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); - var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + // If the arg is not inlineable, we have to evaluate it in the current scope with a temp var + var temp = arg && !ts.isSimpleInlineableExpression(arg) && !isInlineable ? factory.createTempVariable(hoistVariableDeclaration) : undefined; + var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), + /*typeArguments*/ undefined, + /*argumentsArray*/ []); + var requireCall = factory.createCallExpression(factory.createIdentifier("require"), + /*typeArguments*/ undefined, temp ? [temp] : arg ? [arg] : []); if (ts.getESModuleInterop(compilerOptions)) { requireCall = emitHelpers().createImportStarHelper(requireCall); } @@ -107351,14 +107599,9 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)])); - // if there is a lexical 'this' in the import call arguments, ensure we indicate - // that this new function expression indicates it captures 'this' so that the - // es2015 transformer will properly substitute 'this' with '_this'. - if (containsLexicalThis) { - ts.setEmitFlags(func, 8 /* EmitFlags.CapturesThis */); - } } - return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + var downleveledImport = factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + return temp === undefined ? downleveledImport : factory.createCommaListExpression([factory.createAssignment(temp, arg), downleveledImport]); } function getHelperExpressionForExport(node, innerExpr) { if (!ts.getESModuleInterop(compilerOptions) || ts.getEmitFlags(node) & 67108864 /* EmitFlags.NeverApplyImportHelper */) { @@ -122531,10 +122774,16 @@ var ts; var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + // We can only reuse emit signatures (i.e. .d.ts signatures) if the .d.ts file is unchanged, + // which will eg be depedent on change in options like declarationDir and outDir options are unchanged. + // We need to look in oldState.compilerOptions, rather than oldCompilerOptions (i.e.we need to disregard useOldState) because + // oldCompilerOptions can be undefined if there was change in say module from None to some other option + // which would make useOldState as false since we can now use reference maps that are needed to track what to emit, what to check etc + // but that option change does not affect d.ts file name so emitSignatures should still be reused. var canCopyEmitSignatures = compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && !outFilePath && - !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); if (useOldState) { // Copy old state's changed files set (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); @@ -123749,7 +123998,7 @@ var ts; var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* CharacterCodes.slash */; if (isNonDirectorySeparatorRoot && dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths - pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart + pathPartForUserCheck.search(/[a-zA-Z]\$\//) === 0) { // Dos style nextPart nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1); if (nextDirectorySeparator === -1) { // ignore "//vda1cs4850/c$/folderAtRoot" @@ -125003,7 +125252,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_36 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -125027,9 +125276,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_12 = _loop_36(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_12 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -125098,7 +125347,7 @@ var ts; } function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - var _loop_37 = function (patternText_1) { + var _loop_36 = function (patternText_1) { var pattern = ts.normalizePath(patternText_1); var indexOfStar = pattern.indexOf("*"); // In module resolution, if `pattern` itself has an extension, a file with that extension is looked up directly, @@ -125165,9 +125414,9 @@ var ts; }; for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { var patternText_1 = _a[_i]; - var state_13 = _loop_37(patternText_1); - if (typeof state_13 === "object") - return state_13.value; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } function validateEnding(_a) { @@ -125255,15 +125504,21 @@ var ts; return undefined; } function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { + var normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPaths === undefined) { + return undefined; + } + var normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePaths = ts.flatMap(normalizedSourcePaths, function (sourcePath) { + return ts.map(normalizedTargetPaths, function (targetPath) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName)); }); + }); + var shortest = ts.min(relativePaths, ts.compareNumberOfDirectorySeparators); + if (!shortest) { return undefined; } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs - ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions) - : ts.removeFileExtension(relativePath); + ? removeExtensionAndIndexPostFix(shortest, ending, compilerOptions) + : ts.removeFileExtension(shortest); } function tryGetModuleNameAsNodeModule(_a, _b, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { var path = _a.path, isRedirect = _a.isRedirect; @@ -125400,8 +125655,8 @@ var ts; } } } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { + function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.mapDefined(rootDirs, function (rootDir) { var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath; }); @@ -127969,8 +128224,15 @@ var ts; } if (buildInfo.program) { // If there are pending changes that are not emitted, project is out of date + // When there are syntax errors, changeFileSet will have list of files changed (irrespective of noEmit) + // But in case of semantic error we need special treatment. + // Checking presence of affectedFilesPendingEmit list is fast and good way to tell if there were semantic errors and file emit was blocked + // But if noEmit is true, affectedFilesPendingEmit will have file list even if there are no semantic errors to preserve list of files to be emitted when running with noEmit false + // So with noEmit set to true, check on semantic diagnostics needs to be explicit as oppose to when it is false when only files pending emit is sufficient if (((_a = buildInfo.program.changeFileSet) === null || _a === void 0 ? void 0 : _a.length) || - (!project.options.noEmit && ((_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length))) { + (!project.options.noEmit ? + (_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length : + ts.some(buildInfo.program.semanticDiagnosticsPerFile, ts.isArray))) { return { type: ts.UpToDateStatusType.OutOfDateBuildInfo, buildInfoFile: buildInfoPath @@ -129151,6 +129413,12 @@ var ts; SemanticClassificationFormat["Original"] = "original"; SemanticClassificationFormat["TwentyTwenty"] = "2020"; })(SemanticClassificationFormat = ts.SemanticClassificationFormat || (ts.SemanticClassificationFormat = {})); + var OrganizeImportsMode; + (function (OrganizeImportsMode) { + OrganizeImportsMode["All"] = "All"; + OrganizeImportsMode["SortAndCombine"] = "SortAndCombine"; + OrganizeImportsMode["RemoveUnused"] = "RemoveUnused"; + })(OrganizeImportsMode = ts.OrganizeImportsMode || (ts.OrganizeImportsMode = {})); var CompletionTriggerKind; (function (CompletionTriggerKind) { /** Completion was triggered by typing an identifier, manual invocation (e.g Ctrl+Space) or via API. */ @@ -130196,6 +130464,8 @@ var ts; return lastTypeNode; } function getContextualTypeFromParentOrAncestorTypeNode(node, checker) { + if (node.flags & (8388608 /* NodeFlags.JSDoc */ & ~262144 /* NodeFlags.JavaScriptFile */)) + return undefined; var contextualType = getContextualTypeFromParent(node, checker); if (contextualType) return contextualType; @@ -132682,6 +132952,10 @@ var ts; return jsx === 2 /* JsxEmit.React */ || jsx === 3 /* JsxEmit.ReactNative */; } ts.jsxModeNeedsExplicitImport = jsxModeNeedsExplicitImport; + function isSourceFileFromLibrary(program, node) { + return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); + } + ts.isSourceFileFromLibrary = isSourceFileFromLibrary; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -135708,7 +135982,7 @@ var ts; if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* CompletionKind.MemberLike */ && - isClassLikeMemberCompletion(symbol, location)) { + isClassLikeMemberCompletion(symbol, location, sourceFile)) { var importAdder = void 0; (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken, formatContext), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder, replacementSpan = _b.replacementSpan); sortText = Completions.SortText.ClassMemberSnippets; // sortText has to be lower priority than the sortText for keywords. See #47852. @@ -135780,7 +136054,7 @@ var ts; data: data, }; } - function isClassLikeMemberCompletion(symbol, location) { + function isClassLikeMemberCompletion(symbol, location, sourceFile) { // TODO: support JS files. if (ts.isInJSFile(location)) { return false; @@ -135814,6 +136088,7 @@ var ts; location.parent.parent && ts.isClassElement(location.parent) && location === location.parent.name && + location.parent.getLastToken(sourceFile) === location.parent.name && ts.isClassLike(location.parent.parent)) || (location.parent && ts.isSyntaxList(location) && @@ -142975,6 +143250,12 @@ var ts; var label = ts.getTargetLabel(node.parent, node.text); return label ? [createDefinitionInfoFromName(typeChecker, label, "label" /* ScriptElementKind.label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 } + if (node.kind === 105 /* SyntaxKind.ReturnKeyword */) { + var functionDeclaration = ts.findAncestor(node.parent, function (n) { + return ts.isClassStaticBlockDeclaration(n) ? "quit" : ts.isFunctionLikeDeclaration(n); + }); + return functionDeclaration ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : undefined; + } if (ts.isStaticModifier(node) && ts.isClassStaticBlockDeclaration(node.parent)) { var classDecl = node.parent.parent; var _c = getSymbol(classDecl, typeChecker, stopAtAlias), symbol_1 = _c.symbol, failedAliasResolution_1 = _c.failedAliasResolution; @@ -143110,13 +143391,16 @@ var ts; if (!baseDeclaration) return; var baseTypeNode = ts.getEffectiveBaseTypeNode(baseDeclaration); - var baseType = baseTypeNode ? typeChecker.getTypeAtLocation(baseTypeNode) : undefined; - if (!baseType) + if (!baseTypeNode) + return; + var expression = ts.skipParentheses(baseTypeNode.expression); + var base = ts.isClassExpression(expression) ? expression.symbol : typeChecker.getSymbolAtLocation(expression); + if (!base) return; var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(classElement.name)); var symbol = ts.hasStaticModifier(classElement) - ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbolAtLocation(baseType.symbol, baseDeclaration), name) - : typeChecker.getPropertyOfType(baseType, name); + ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbol(base), name) + : typeChecker.getPropertyOfType(typeChecker.getDeclaredTypeOfSymbol(base), name); if (!symbol) return; return getDefinitionFromSymbol(typeChecker, symbol, node); @@ -143823,19 +144107,24 @@ var ts; return getCommentOwnerInfoWorker(commentOwner.initializer, options); case 260 /* SyntaxKind.ClassDeclaration */: case 261 /* SyntaxKind.InterfaceDeclaration */: - case 168 /* SyntaxKind.PropertySignature */: case 263 /* SyntaxKind.EnumDeclaration */: case 302 /* SyntaxKind.EnumMember */: case 262 /* SyntaxKind.TypeAliasDeclaration */: return { commentOwner: commentOwner }; + case 168 /* SyntaxKind.PropertySignature */: { + var host_1 = commentOwner; + return host_1.type && ts.isFunctionTypeNode(host_1.type) + ? { commentOwner: commentOwner, parameters: host_1.type.parameters, hasReturn: hasReturn(host_1.type, options) } + : { commentOwner: commentOwner }; + } case 240 /* SyntaxKind.VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; - var host_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + var host_2 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } + return host_2 + ? { commentOwner: commentOwner, parameters: host_2.parameters, hasReturn: hasReturn(host_2, options) } : { commentOwner: commentOwner }; } case 308 /* SyntaxKind.SourceFile */: @@ -143865,7 +144154,7 @@ var ts; } function hasReturn(node, options) { return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && - (ts.isArrowFunction(node) && ts.isExpression(node.body) + (ts.isFunctionTypeNode(node) || ts.isArrowFunction(node) && ts.isExpression(node.body) || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { @@ -144906,23 +145195,39 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { + function organizeImports(sourceFile, formatContext, host, program, preferences, mode) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var shouldSort = mode === "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ || mode === "All" /* OrganizeImportsMode.All */; + var shouldCombine = shouldSort; // These are currently inseparable, but I draw a distinction for clarity and in case we add modes in the future. + var shouldRemove = mode === "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */ || mode === "All" /* OrganizeImportsMode.All */; + var maybeRemove = shouldRemove ? removeUnusedImports : ts.identity; + var maybeCoalesce = shouldCombine ? coalesceImports : ts.identity; + var processImportsOfSameModuleSpecifier = function (importGroup) { + var processedDeclarations = maybeCoalesce(maybeRemove(importGroup, sourceFile, program)); + return shouldSort + ? ts.stableSort(processedDeclarations, function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }) + : processedDeclarations; + }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, sourceFile.statements.filter(ts.isImportDeclaration)); - topLevelImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, coalesceAndOrganizeImports); }); - // All of the old ExportDeclarations in the file, in syntactic order. - var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); - organizeImportsWorker(topLevelExportDecls, coalesceExports); + topLevelImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier); }); + // Exports are always used + if (mode !== "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */) { + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); + } for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; if (!ambientModule.body) continue; var ambientModuleImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, ambientModule.body.statements.filter(ts.isImportDeclaration)); - ambientModuleImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, coalesceAndOrganizeImports); }); - var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); - organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + ambientModuleImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier); }); + // Exports are always used + if (mode !== "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */) { + var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + } } return changeTracker.getChanges(); function organizeImportsWorker(oldImportDecls, coalesce) { @@ -144935,8 +145240,12 @@ var ts; // Consider: we could do a more careful check that this trivia is actually a header, // but the consequences of being wrong are very minor. ts.suppressLeadingTrivia(oldImportDecls[0]); - var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); - var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var oldImportGroups = shouldCombine + ? ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }) + : [oldImportDecls]; + var sortedImportGroups = shouldSort + ? ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }) + : oldImportGroups; var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) ? coalesce(importGroup) @@ -145000,11 +145309,7 @@ var ts; } return false; } - function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { - // As a precaution, consider unused import detection to be destructive (GH #43051) - if (skipDestructiveCodeActions) { - return oldImports; - } + function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); @@ -145860,7 +146165,7 @@ var ts; return bestMatch; } function betterMatch(a, b) { - return ts.min(a, b, compareMatches); + return ts.min([a, b], compareMatches); } function compareMatches(a, b) { return a === undefined ? 1 /* Comparison.GreaterThan */ : b === undefined ? -1 /* Comparison.LessThan */ @@ -146469,8 +146774,8 @@ var ts; } if (ts.scanner.getToken() === 15 /* SyntaxKind.TemplateHead */) { var stack = [ts.scanner.getToken()]; - var token = ts.scanner.scan(); loop: while (ts.length(stack)) { + var token = ts.scanner.scan(); switch (token) { case 1 /* SyntaxKind.EndOfFileToken */: break loop; @@ -146498,7 +146803,6 @@ var ts; } break; } - token = ts.scanner.scan(); } nextToken(); } @@ -148977,7 +149281,7 @@ var ts; tags = signature.getJsDocTags(); if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) { documentation = allSignatures[0].getDocumentationComment(typeChecker); - tags = allSignatures[0].getJsDocTags(); + tags = allSignatures[0].getJsDocTags().filter(function (tag) { return tag.name !== "deprecated"; }); // should only include @deprecated JSDoc tag on the first overload (#49368) } } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -149320,7 +149624,7 @@ var ts; return false; } function shouldRescanJsxText(node) { - return ts.isJsxText(node); + return ts.isJsxText(node) || ts.isJsxElement(node) && (lastTokenInfo === null || lastTokenInfo === void 0 ? void 0 : lastTokenInfo.token.kind) === 11 /* SyntaxKind.JsxText */; } function shouldRescanSlashToken(container) { return container.kind === 13 /* SyntaxKind.RegularExpressionLiteral */; @@ -150089,10 +150393,10 @@ var ts; !nodeIsInDecoratorContext(context.nextTokenParent); } function nodeIsInDecoratorContext(node) { - while (ts.isExpressionNode(node)) { + while (node && ts.isExpression(node)) { node = node.parent; } - return node.kind === 167 /* SyntaxKind.Decorator */; + return node && node.kind === 167 /* SyntaxKind.Decorator */; } function isStartOfVariableDeclarationList(context) { return context.currentTokenParent.kind === 258 /* SyntaxKind.VariableDeclarationList */ && @@ -153010,6 +153314,26 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } + function endPositionToDeleteNodeInList(sourceFile, node, prevNode, nextNode) { + var end = startPositionToDeleteNodeInList(sourceFile, nextNode); + if (prevNode === undefined || ts.positionsAreOnSameLine(getAdjustedEndPosition(sourceFile, node, {}), end, sourceFile)) { + return end; + } + var token = ts.findPrecedingToken(nextNode.getStart(sourceFile), sourceFile); + if (isSeparator(node, token)) { + var prevToken = ts.findPrecedingToken(node.getStart(sourceFile), sourceFile); + if (isSeparator(prevNode, prevToken)) { + var pos = ts.skipTrivia(sourceFile.text, token.getEnd(), /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + if (ts.positionsAreOnSameLine(prevToken.getStart(sourceFile), token.getStart(sourceFile), sourceFile)) { + return ts.isLineBreak(sourceFile.text.charCodeAt(pos - 1)) ? pos - 1 : pos; + } + if (ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { + return pos; + } + } + } + return end; + } function getClassOrObjectBraceEnds(cls, sourceFile) { var open = ts.findChildOfKind(cls, 18 /* SyntaxKind.OpenBraceToken */, sourceFile); var close = ts.findChildOfKind(cls, 19 /* SyntaxKind.CloseBraceToken */, sourceFile); @@ -153567,7 +153891,7 @@ var ts; deletedNodesInLists.add(node); changes.deleteRange(sourceFile, { pos: startPositionToDeleteNodeInList(sourceFile, node), - end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : endPositionToDeleteNodeInList(sourceFile, node, containingList[index - 1], containingList[index + 1]), }); } })(textChanges = ts.textChanges || (ts.textChanges = {})); @@ -154037,6 +154361,15 @@ var ts; }); } function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { + if (ts.isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) { + var exprType = checker.getTypeAtLocation(insertionSite); + var asyncIter = checker.getAsyncIterableType(); + if (asyncIter && checker.isTypeAssignableTo(exprType, asyncIter)) { + var forOf = insertionSite.parent; + changeTracker.replaceNode(sourceFile, forOf, ts.factory.updateForOfStatement(forOf, ts.factory.createToken(133 /* SyntaxKind.AwaitKeyword */), forOf.initializer, forOf.expression, forOf.statement)); + return; + } + } if (ts.isBinaryExpression(insertionSite)) { for (var _i = 0, _a = [insertionSite.left, insertionSite.right]; _i < _a.length; _i++) { var side = _a[_i]; @@ -157762,6 +158095,143 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixImportNonExportedMember"; + var errorCodes = [ + ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixId], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program; + var info = getInfo(sourceFile, span.start, program); + if (info === undefined) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, program, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId, ts.Diagnostics.Export_all_referenced_locals)]; + }, + getAllCodeActions: function (context) { + var program = context.program; + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var exports = new ts.Map(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, program); + if (info === undefined) + return undefined; + var exportName = info.exportName, node = info.node, moduleSourceFile = info.moduleSourceFile; + if (tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly) === undefined && ts.canHaveExportModifier(node)) { + changes.insertExportModifier(moduleSourceFile, node); + } + else { + var moduleExports = exports.get(moduleSourceFile) || { typeOnlyExports: [], exports: [] }; + if (exportName.isTypeOnly) { + moduleExports.typeOnlyExports.push(exportName); + } + else { + moduleExports.exports.push(exportName); + } + exports.set(moduleSourceFile, moduleExports); + } + }); + exports.forEach(function (moduleExports, moduleSourceFile) { + var exportDeclaration = tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ true); + if (exportDeclaration && exportDeclaration.isTypeOnly) { + doChanges(changes, program, moduleSourceFile, moduleExports.typeOnlyExports, exportDeclaration); + doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ false)); + } + else { + doChanges(changes, program, moduleSourceFile, __spreadArray(__spreadArray([], moduleExports.exports, true), moduleExports.typeOnlyExports, true), exportDeclaration); + } + }); + })); + } + }); + function getInfo(sourceFile, pos, program) { + var _a; + var token = ts.getTokenAtPosition(sourceFile, pos); + if (ts.isIdentifier(token)) { + var importDeclaration = ts.findAncestor(token, ts.isImportDeclaration); + if (importDeclaration === undefined) + return undefined; + var moduleSpecifier = ts.isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier.text : undefined; + if (moduleSpecifier === undefined) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, moduleSpecifier, /*mode*/ undefined); + if (resolvedModule === undefined) + return undefined; + var moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName); + if (moduleSourceFile === undefined || ts.isSourceFileFromLibrary(program, moduleSourceFile)) + return undefined; + var moduleSymbol = moduleSourceFile.symbol; + var locals = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals; + if (locals === undefined) + return undefined; + var localSymbol = locals.get(token.escapedText); + if (localSymbol === undefined) + return undefined; + var node = getNodeOfSymbol(localSymbol); + if (node === undefined) + return undefined; + var exportName = { node: token, isTypeOnly: ts.isTypeDeclaration(node) }; + return { exportName: exportName, node: node, moduleSourceFile: moduleSourceFile, moduleSpecifier: moduleSpecifier }; + } + return undefined; + } + function doChange(changes, program, _a) { + var exportName = _a.exportName, node = _a.node, moduleSourceFile = _a.moduleSourceFile; + var exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); + if (exportDeclaration) { + updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]); + } + else if (ts.canHaveExportModifier(node)) { + changes.insertExportModifier(moduleSourceFile, node); + } + else { + createExport(changes, program, moduleSourceFile, [exportName]); + } + } + function doChanges(changes, program, sourceFile, moduleExports, node) { + if (ts.length(moduleExports)) { + if (node) { + updateExport(changes, program, sourceFile, node, moduleExports); + } + else { + createExport(changes, program, sourceFile, moduleExports); + } + } + } + function tryGetExportDeclaration(sourceFile, isTypeOnly) { + var predicate = function (node) { + return ts.isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); + }; + return ts.findLast(sourceFile.statements, predicate); + } + function updateExport(changes, program, sourceFile, node, names) { + var namedExports = node.exportClause && ts.isNamedExports(node.exportClause) ? node.exportClause.elements : ts.factory.createNodeArray([]); + var allowTypeModifier = !node.isTypeOnly && !!(program.getCompilerOptions().isolatedModules || ts.find(namedExports, function (e) { return e.isTypeOnly; })); + changes.replaceNode(sourceFile, node, ts.factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, ts.factory.createNamedExports(ts.factory.createNodeArray(__spreadArray(__spreadArray([], namedExports, true), createExportSpecifiers(names, allowTypeModifier), true), /*hasTrailingComma*/ namedExports.hasTrailingComma)), node.moduleSpecifier, node.assertClause)); + } + function createExport(changes, program, sourceFile, names) { + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ !!program.getCompilerOptions().isolatedModules)), /*moduleSpecifier*/ undefined, /*assertClause*/ undefined)); + } + function createExportSpecifiers(names, allowTypeModifier) { + return ts.factory.createNodeArray(ts.map(names, function (n) { return ts.factory.createExportSpecifier(allowTypeModifier && n.isTypeOnly, /*propertyName*/ undefined, n.node); })); + } + function getNodeOfSymbol(symbol) { + if (symbol.valueDeclaration === undefined) { + return ts.firstOrUndefined(symbol.declarations); + } + var declaration = symbol.valueDeclaration; + var variableStatement = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : undefined; + return variableStatement && ts.length(variableStatement.declarationList.declarations) === 1 ? variableStatement : declaration; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -158292,7 +158762,7 @@ var ts; var argIndex = ts.findIndex(parent.parent.arguments, function (arg) { return arg === parent; }); if (argIndex < 0) return undefined; - var signature = ts.singleOrUndefined(checker.getSignaturesOfType(checker.getTypeAtLocation(parent.parent.expression), 0 /* SignatureKind.Call */)); + var signature = checker.getResolvedSignature(parent.parent); if (!(signature && signature.declaration && signature.parameters[argIndex])) return undefined; var param = signature.parameters[argIndex].valueDeclaration; @@ -158339,13 +158809,13 @@ var ts; if (ts.isIdentifier(token) && ts.isCallExpression(parent.parent)) { var moduleDeclaration = ts.find(symbol.declarations, ts.isModuleDeclaration); var moduleDeclarationSourceFile = moduleDeclaration === null || moduleDeclaration === void 0 ? void 0 : moduleDeclaration.getSourceFile(); - if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { + if (moduleDeclaration && moduleDeclarationSourceFile && !ts.isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { return { kind: InfoKind.Function, token: token, call: parent.parent, sourceFile: sourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleDeclaration }; } var moduleSourceFile = ts.find(symbol.declarations, ts.isSourceFile); if (sourceFile.commonJsModuleIndicator) return undefined; - if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) { + if (moduleSourceFile && !ts.isSourceFileFromLibrary(program, moduleSourceFile)) { return { kind: InfoKind.Function, token: token, call: parent.parent, sourceFile: moduleSourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleSourceFile }; } } @@ -158355,7 +158825,7 @@ var ts; return undefined; // Prefer to change the class instead of the interface if they are merged var declaration = classDeclaration || ts.find(symbol.declarations, function (d) { return ts.isInterfaceDeclaration(d) || ts.isTypeLiteralNode(d); }); - if (declaration && !isSourceFileFromLibrary(program, declaration.getSourceFile())) { + if (declaration && !ts.isSourceFileFromLibrary(program, declaration.getSourceFile())) { var makeStatic = !ts.isTypeLiteralNode(declaration) && (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); if (makeStatic && (ts.isPrivateIdentifier(token) || ts.isInterfaceDeclaration(declaration))) return undefined; @@ -158367,14 +158837,11 @@ var ts; return { kind: InfoKind.TypeLikeDeclaration, token: token, call: call, modifierFlags: modifierFlags, parentDeclaration: declaration, declSourceFile: declSourceFile, isJSFile: isJSFile }; } var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); - if (enumDeclaration && !(leftExpressionType.flags & 1056 /* TypeFlags.EnumLike */) && !ts.isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { + if (enumDeclaration && !(leftExpressionType.flags & 1056 /* TypeFlags.EnumLike */) && !ts.isPrivateIdentifier(token) && !ts.isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { return { kind: InfoKind.Enum, token: token, parentDeclaration: enumDeclaration }; } return undefined; } - function isSourceFileFromLibrary(program, node) { - return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); - } function getActionsForMissingMemberDeclaration(context, info) { return info.isJSFile ? ts.singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : createActionsForAddMissingMemberInTypeScriptFile(context, info); @@ -163800,8 +164267,8 @@ var ts; var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; - var description = functionExtraction.description; if (refactor.refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + var description = functionExtraction.description; if (functionExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will @@ -163825,15 +164292,15 @@ var ts; } } if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + var description = constantExtraction.description; if (constantExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will // preferentially go into nearer scopes - var description_1 = constantExtraction.description; - if (!usedConstantNames.has(description_1)) { - usedConstantNames.set(description_1, true); + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); constantActions.push({ - description: description_1, + description: description, name: "constant_scope_".concat(i), kind: extractConstantAction.kind }); @@ -163978,7 +164445,6 @@ var ts; var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, adjustedSpan); // Do the same for the ending position var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, adjustedSpan); - var declarations = []; // We'll modify these flags as we walk the tree to collect data // about what things need to be done as part of the extraction. var rangeFacts = RangeFacts.None; @@ -164021,7 +164487,7 @@ var ts; // the expression. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } - return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations, thisNode: thisNode } }; + return { targetRange: { range: statements, facts: rangeFacts, thisNode: thisNode } }; } if (ts.isReturnStatement(start) && !start.expression) { // Makes no sense to extract an expression-less return statement. @@ -164033,7 +164499,7 @@ var ts; if (errors) { return { errors: errors }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations, thisNode: thisNode } }; // TODO: GH#18217 + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode: thisNode } }; // TODO: GH#18217 /** * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. * @param node The unrefined extraction node. @@ -164045,10 +164511,10 @@ var ts; } } else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { - var declarations_6 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; + var declarations = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, declarations_5 = declarations_6; _i < declarations_5.length; _i++) { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; if (declaration.initializer) { numInitializers++; @@ -164148,7 +164614,6 @@ var ts; (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } - declarations.push(node.symbol); } // Some things can't be extracted in certain situations switch (node.kind) { @@ -165873,7 +166338,7 @@ var ts; function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); var prologueDirectives = ts.takeWhile(oldFile.statements, ts.isPrologueDirective); - if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + if (oldFile.externalModuleIndicator === undefined && oldFile.commonJsModuleIndicator === undefined && usage.oldImportsNeededByNewFile.size() === 0) { deleteMovedStatements(oldFile, toMove.ranges, changes); return __spreadArray(__spreadArray([], prologueDirectives, true), toMove.all, true); } @@ -166114,7 +166579,12 @@ var ts; switch (name.kind) { case 79 /* SyntaxKind.Identifier */: if (isUnused(name)) { - changes.delete(sourceFile, name); + if (varDecl.initializer && ts.isRequireCall(varDecl.initializer, /*requireStringLiteralLikeArgument*/ true)) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && ts.length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); + } + else { + changes.delete(sourceFile, name); + } } break; case 204 /* SyntaxKind.ArrayBindingPattern */: @@ -166346,6 +166816,9 @@ var ts; ts.copyEntries(this.map, clone.map); return clone; }; + SymbolSet.prototype.size = function () { + return this.map.size; + }; return SymbolSet; }()); function isTopLevelDeclaration(node) { @@ -166434,7 +166907,8 @@ var ts; if (useEs6Exports) { return !ts.isExpressionStatement(decl) && ts.hasSyntacticModifier(decl, 1 /* ModifierFlags.Export */) || !!(name && ((_a = sourceFile.symbol.exports) === null || _a === void 0 ? void 0 : _a.has(name.escapedText))); } - return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + return !!sourceFile.symbol && !!sourceFile.symbol.exports && + getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); } function addExport(decl, useEs6Exports) { return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); @@ -168194,8 +168668,8 @@ var ts; tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); } }; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; _loop_20(declaration); } } @@ -168221,8 +168695,8 @@ var ts; if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); }; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; _loop_21(declaration); } } @@ -169392,12 +169866,14 @@ var ts; return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } function organizeImports(args, formatOptions, preferences) { + var _a; if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(args.type === "file"); var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); + var mode = (_a = args.mode) !== null && _a !== void 0 ? _a : (args.skipDestructiveCodeActions ? "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ : "All" /* OrganizeImportsMode.All */); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, mode); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index b5f076b36596e..91b7c1f901739 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -5399,9 +5399,9 @@ declare namespace ts { /** If provided, called with Diagnostic message that informs about change in watch status */ onWatchStatusChange?(diagnostic: Diagnostic, newLine: string, options: CompilerOptions, errorCount?: number): void; /** Used to watch changes in source files, missing files needed to update the program or config file */ - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: CompilerOptions): FileWatcher; + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: CompilerOptions): FileWatcher; + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; /** If provided, will be used to reset existing delayed compilation */ @@ -6032,8 +6032,15 @@ declare namespace ts { type: "file"; fileName: string; } + enum OrganizeImportsMode { + All = "All", + SortAndCombine = "SortAndCombine", + RemoveUnused = "RemoveUnused" + } interface OrganizeImportsArgs extends CombinedCodeFixScope { + /** @deprecated Use `mode` instead */ skipDestructiveCodeActions?: boolean; + mode?: OrganizeImportsMode; } type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<" | "#" | " "; enum CompletionTriggerKind { diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 0b6841d281c66..576ee090df80f 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -99,7 +99,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 = "".concat(ts.versionMajorMinor, ".1-beta"); + ts.version = "".concat(ts.versionMajorMinor, ".2-rc"); /* @internal */ var Comparison; (function (Comparison) { @@ -1891,8 +1891,8 @@ var ts; return compareValues(a === null || a === void 0 ? void 0 : a.start, b === null || b === void 0 ? void 0 : b.start) || compareValues(a === null || a === void 0 ? void 0 : a.length, b === null || b === void 0 ? void 0 : b.length); } ts.compareTextSpans = compareTextSpans; - function min(a, b, compare) { - return compare(a, b) === -1 /* Comparison.LessThan */ ? a : b; + function min(items, compare) { + return reduceLeft(items, function (x, y) { return compare(x, y) === -1 /* Comparison.LessThan */ ? x : y; }); } ts.min = min; /** @@ -3205,11 +3205,13 @@ var ts; // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers // > MUST NOT include leading zeroes. var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; // https://semver.org/#spec-item-10 // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated // > identifiers immediately following the patch or pre-release version. Identifiers MUST // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var buildPartRegExp = /^[a-z0-9-]+$/i; // https://semver.org/#spec-item-9 // > Numeric identifiers MUST NOT include leading zeroes. var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; @@ -3229,13 +3231,15 @@ var ts; ts.Debug.assert(major >= 0, "Invalid argument: major"); ts.Debug.assert(minor >= 0, "Invalid argument: minor"); ts.Debug.assert(patch >= 0, "Invalid argument: patch"); - ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); - ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + var prereleaseArray = prerelease ? ts.isArray(prerelease) ? prerelease : prerelease.split(".") : ts.emptyArray; + var buildArray = build ? ts.isArray(build) ? build : build.split(".") : ts.emptyArray; + ts.Debug.assert(ts.every(prereleaseArray, function (s) { return prereleasePartRegExp.test(s); }), "Invalid argument: prerelease"); + ts.Debug.assert(ts.every(buildArray, function (s) { return buildPartRegExp.test(s); }), "Invalid argument: build"); this.major = major; this.minor = minor; this.patch = patch; - this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; - this.build = build ? build.split(".") : ts.emptyArray; + this.prerelease = prereleaseArray; + this.build = buildArray; } Version.tryParse = function (text) { var result = tryParseComponents(text); @@ -3274,6 +3278,10 @@ var ts; default: return ts.Debug.assertNever(field); } }; + Version.prototype.with = function (fields) { + var _a = fields.major, major = _a === void 0 ? this.major : _a, _b = fields.minor, minor = _b === void 0 ? this.minor : _b, _c = fields.patch, patch = _c === void 0 ? this.patch : _c, _d = fields.prerelease, prerelease = _d === void 0 ? this.prerelease : _d, _e = fields.build, build = _e === void 0 ? this.build : _e; + return new Version(major, minor, patch, prerelease, build); + }; Version.prototype.toString = function () { var result = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); if (ts.some(this.prerelease)) @@ -3282,7 +3290,7 @@ var ts; result += "+".concat(this.build.join(".")); return result; }; - Version.zero = new Version(0, 0, 0); + Version.zero = new Version(0, 0, 0, ["0"]); return Version; }()); ts.Version = Version; @@ -3365,6 +3373,10 @@ var ts; } return undefined; }; + /** + * Tests whether a version matches the range. This is equivalent to `satisfies(version, range, { includePrerelease: true })`. + * in `node-semver`. + */ VersionRange.prototype.test = function (version) { if (typeof version === "string") version = new Version(version); @@ -3475,19 +3487,20 @@ var ts; break; case "<": case ">=": - comparators.push(createComparator(operator, version)); + comparators.push(isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version.with({ prerelease: "0" })) : + createComparator(operator, version)); break; case "<=": case ">": - comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : - isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major").with({ prerelease: "0" })) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor").with({ prerelease: "0" })) : createComparator(operator, version)); break; case "=": case undefined: if (isWildcard(minor) || isWildcard(patch)) { - comparators.push(createComparator(">=", version)); - comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + comparators.push(createComparator(">=", version.with({ prerelease: "0" }))); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor").with({ prerelease: "0" }))); } else { comparators.push(createComparator("=", version)); @@ -5096,8 +5109,8 @@ var ts; NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAccessInAsync"] = 2048] = "MethodWithSuperPropertyAccessInAsync"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAssignmentInAsync"] = 4096] = "MethodWithSuperPropertyAssignmentInAsync"; NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; @@ -6732,7 +6745,7 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; + var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; var pollingWatches = new ts.Map(); var fsWatches = new ts.Map(); var fsWatchesRecursive = new ts.Map(); @@ -6798,8 +6811,8 @@ var ts; return useNonPollingWatchers ? // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : - // Default to do not use fixed polling interval - { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.UseFsEvents }; + // Default to using fs events + { watchFile: ts.WatchFileKind.UseFsEvents }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -7071,7 +7084,6 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, - defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, inodeWatching: isLinuxOrMacOs, sysLog: sysLog, }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; @@ -9582,6 +9594,10 @@ var ts; Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted: diag(6399, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399", "Project '{0}' is out of date because buildinfo file '{1}' indicates that some of the changes were not emitted"), Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files: diag(6400, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400", "Project '{0}' is up to date but needs to update timestamps of output files that are older than input files"), Project_0_is_out_of_date_because_there_was_error_reading_file_1: diag(6401, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401", "Project '{0}' is out of date because there was error reading file '{1}'"), + Resolving_in_0_mode_with_conditions_1: diag(6402, ts.DiagnosticCategory.Message, "Resolving_in_0_mode_with_conditions_1_6402", "Resolving in {0} mode with conditions {1}."), + Matched_0_condition_1: diag(6403, ts.DiagnosticCategory.Message, "Matched_0_condition_1_6403", "Matched '{0}' condition '{1}'."), + Using_0_subpath_1_with_target_2: diag(6404, ts.DiagnosticCategory.Message, "Using_0_subpath_1_with_target_2_6404", "Using '{0}' subpath '{1}' with target '{2}'."), + Saw_non_matching_condition_0: diag(6405, ts.DiagnosticCategory.Message, "Saw_non_matching_condition_0_6405", "Saw non-matching condition '{0}'."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -9898,6 +9914,8 @@ var ts; Remove_type_from_import_of_0_from_1: diag(90056, ts.DiagnosticCategory.Message, "Remove_type_from_import_of_0_from_1_90056", "Remove 'type' from import of '{0}' from \"{1}\""), Add_import_from_0: diag(90057, ts.DiagnosticCategory.Message, "Add_import_from_0_90057", "Add import from \"{0}\""), Update_import_from_0: diag(90058, ts.DiagnosticCategory.Message, "Update_import_from_0_90058", "Update import from \"{0}\""), + Export_0_from_module_1: diag(90059, ts.DiagnosticCategory.Message, "Export_0_from_module_1_90059", "Export '{0}' from module '{1}'"), + Export_all_referenced_locals: diag(90060, ts.DiagnosticCategory.Message, "Export_all_referenced_locals_90060", "Export all referenced locals"), 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}"), @@ -11355,7 +11373,7 @@ var ts; return -1; } function peekExtendedUnicodeEscape() { - if (languageVersion >= 2 /* ScriptTarget.ES2015 */ && codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { + if (codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { var start_2 = pos; pos += 3; var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); @@ -21658,6 +21676,32 @@ var ts; return parameter.kind === 343 /* SyntaxKind.JSDocParameterTag */ ? (_a = parameter.typeExpression) === null || _a === void 0 ? void 0 : _a.type : parameter.type; } ts.getParameterTypeNode = getParameterTypeNode; + function isTypeDeclaration(node) { + switch (node.kind) { + case 165 /* SyntaxKind.TypeParameter */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: + return true; + case 270 /* SyntaxKind.ImportClause */: + return node.isTypeOnly; + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: + return node.parent.parent.isTypeOnly; + default: + return false; + } + } + ts.isTypeDeclaration = isTypeDeclaration; + function canHaveExportModifier(node) { + return ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) || isTypeDeclaration(node) || (ts.isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node)); + } + ts.canHaveExportModifier = canHaveExportModifier; })(ts || (ts = {})); /* @internal */ var ts; @@ -21666,13 +21710,11 @@ var ts; * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator. */ function createBaseNodeFactory() { - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name return { createBaseSourceFileNode: createBaseSourceFileNode, createBaseIdentifierNode: createBaseIdentifierNode, @@ -23136,7 +23178,7 @@ var ts; return node; } // @api - function createIdentifier(text, typeArguments, originalKeywordKind) { + function createIdentifier(text, typeArguments, originalKeywordKind, hasExtendedUnicodeEscape) { var node = createBaseIdentifier(text, originalKeywordKind); if (typeArguments) { // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations @@ -23145,6 +23187,10 @@ var ts; if (node.originalKeywordKind === 133 /* SyntaxKind.AwaitKeyword */) { node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } + if (hasExtendedUnicodeEscape) { + node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + } return node; } // @api @@ -27600,11 +27646,9 @@ var ts; rawTextScanner.setText("`" + rawText + "`"); break; case 15 /* SyntaxKind.TemplateHead */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("`" + rawText + "${"); break; case 16 /* SyntaxKind.TemplateMiddle */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("}" + rawText + "${"); break; case 17 /* SyntaxKind.TemplateTail */: @@ -27963,7 +28007,6 @@ var ts; return node; } ts.createInputFiles = createInputFiles; - // tslint:disable-next-line variable-name var SourceMapSource; /** * Create an external source map source file reference @@ -28755,6 +28798,8 @@ var ts; // - The verb (`next`, `throw`, or `return` method) to delegate to the expression // of a `yield*`. // - The result of evaluating the verb delegated to the expression of a `yield*`. + // g A temporary variable that holds onto the generator object until the generator + // is started, allowing it to also act as the `suspendedStart` state. // // functions: // verb(n) Creates a bound callback to the `step` function for opcode `n`. @@ -28793,7 +28838,7 @@ var ts; importName: "__generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; // ES Module Helpers ts.createBindingHelper = { @@ -32097,13 +32142,11 @@ var ts; var scanner = ts.createScanner(99 /* ScriptTarget.Latest */, /*skipTrivia*/ true); var disallowInAndDecoratorContext = 4096 /* NodeFlags.DisallowInContext */ | 16384 /* NodeFlags.DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name function countNode(node) { nodeCount++; return node; @@ -33079,8 +33122,9 @@ var ts; // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); var text = internIdentifier(scanner.getTokenValue()); + var hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape(); nextTokenWithoutCheck(); - return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos); + return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind, hasExtendedUnicodeEscape), pos); } if (token() === 80 /* SyntaxKind.PrivateIdentifier */) { parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); @@ -42219,12 +42263,23 @@ var ts; } function writeConfigurations() { // Filter applicable options to place in the file - var categorizedOptions = ts.createMultiMap(); + var categorizedOptions = new ts.Map(); + // Set allowed categories in order + categorizedOptions.set(ts.Diagnostics.Projects, []); + categorizedOptions.set(ts.Diagnostics.Language_and_Environment, []); + categorizedOptions.set(ts.Diagnostics.Modules, []); + categorizedOptions.set(ts.Diagnostics.JavaScript_Support, []); + categorizedOptions.set(ts.Diagnostics.Emit, []); + categorizedOptions.set(ts.Diagnostics.Interop_Constraints, []); + categorizedOptions.set(ts.Diagnostics.Type_Checking, []); + categorizedOptions.set(ts.Diagnostics.Completeness, []); for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { var option = optionDeclarations_1[_i]; - var category = option.category; if (isAllowedOptionForOutput(option)) { - categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + var listForCategory = categorizedOptions.get(option.category); + if (!listForCategory) + categorizedOptions.set(option.category, listForCategory = []); + listForCategory.push(option); } } // Serialize all options and their descriptions @@ -42235,7 +42290,7 @@ var ts; if (entries.length !== 0) { entries.push({ value: "" }); } - entries.push({ value: "/* ".concat(category, " */") }); + entries.push({ value: "/* ".concat(ts.getLocaleSpecificMessage(category), " */") }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -44277,6 +44332,9 @@ var ts; requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; + if (traceEnabled && ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) <= ts.ModuleResolutionKind.NodeNext) { + trace(host, ts.Diagnostics.Resolving_in_0_mode_with_conditions_1, features & NodeResolutionFeatures.EsmMode ? "ESM" : "CJS", conditions.map(function (c) { return "'".concat(c, "'"); }).join(", ")); + } var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { @@ -44866,7 +44924,7 @@ var ts; } if (mainExport) { var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false); - return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false, "."); } } else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) { @@ -44946,7 +45004,7 @@ var ts; var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!ts.endsWith(moduleName, ts.directorySeparator) && moduleName.indexOf("*") === -1 && ts.hasProperty(lookupTable, moduleName)) { var target = lookupTable[moduleName]; - return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName); } var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), comparePatternKeys); for (var _i = 0, expandingKeys_1 = expandingKeys; _i < expandingKeys_1.length; _i++) { @@ -44955,17 +45013,17 @@ var ts; var target = lookupTable[potentialTarget]; var starPos = potentialTarget.indexOf("*"); var subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.endsWith(potentialTarget, "*") && ts.startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length - 1); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.startsWith(moduleName, potentialTarget)) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false, potentialTarget); } } function matchesPatternWithTrailer(target, name) { @@ -44982,7 +45040,7 @@ var ts; */ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) { return loadModuleFromTargetImportOrExport; - function loadModuleFromTargetImportOrExport(target, subpath, pattern) { + function loadModuleFromTargetImportOrExport(target, subpath, pattern, key) { if (typeof target === "string") { if (!pattern && subpath.length > 0 && !ts.endsWith(target, "/")) { if (state.traceEnabled) { @@ -44993,6 +45051,8 @@ var ts; if (!ts.startsWith(target, "./")) { if (isImports && !ts.startsWith(target, "../") && !ts.startsWith(target, "/") && !ts.isRootedDiskPath(target)) { var combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath; + traceIfEnabled(state, ts.Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup); + traceIfEnabled(state, ts.Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/"); var result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, [extensions], redirectedReference); return toSearchResult(result.resolvedModule ? { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId, originalPath: result.resolvedModule.originalPath } : undefined); } @@ -45019,6 +45079,9 @@ var ts; } return toSearchResult(/*value*/ undefined); } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); + } var finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); var inputLink = tryLoadInputFileForPath(finalPath, subpath, ts.combinePaths(scope.packageDirectory, "package.json"), isImports); if (inputLink) @@ -45028,14 +45091,18 @@ var ts; else if (typeof target === "object" && target !== null) { // eslint-disable-line no-null/no-null if (!Array.isArray(target)) { for (var _i = 0, _a = ts.getOwnKeys(target); _i < _a.length; _i++) { - var key = _a[_i]; - if (key === "default" || state.conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(state.conditions, key)) { - var subTarget = target[key]; - var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern); + var condition = _a[_i]; + if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) { + traceIfEnabled(state, ts.Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition); + var subTarget = target[condition]; + var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key); if (result) { return result; } } + else { + traceIfEnabled(state, ts.Diagnostics.Saw_non_matching_condition_0, condition); + } } return undefined; } @@ -45048,7 +45115,7 @@ var ts; } for (var _b = 0, target_2 = target; _b < target_2.length; _b++) { var elem = target_2[_b]; - var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern); + var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern, key); if (result) { return result; } @@ -45464,6 +45531,15 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } + function traceIfEnabled(state, diagnostic) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (state.traceEnabled) { + trace.apply(void 0, __spreadArray([state.host, diagnostic], args, false)); + } + } })(ts || (ts = {})); /* @internal */ var ts; @@ -49055,8 +49131,6 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; - IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var RecursionFlags; (function (RecursionFlags) { @@ -49475,6 +49549,12 @@ var ts; getOptionalType: function () { return optionalType; }, getPromiseType: function () { return getGlobalPromiseType(/*reportErrors*/ false); }, getPromiseLikeType: function () { return getGlobalPromiseLikeType(/*reportErrors*/ false); }, + getAsyncIterableType: function () { + var type = getGlobalAsyncIterableType(/*reportErrors*/ false); + if (type === emptyGenericType) + return undefined; + return type; + }, isSymbolAccessible: isSymbolAccessible, isArrayType: isArrayType, isTupleType: isTupleType, @@ -50312,9 +50392,9 @@ var ts; return symbol; } if (symbol.flags & 2097152 /* SymbolFlags.Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { + var targetFlags = getAllSymbolFlags(symbol); + // `targetFlags` will be `SymbolFlags.All` if an error occurred in alias resolution; this avoids cascading errors + if (targetFlags & meaning) { return symbol; } } @@ -50947,8 +51027,8 @@ var ts; !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && + !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; var suggestedLib = void 0; @@ -51035,7 +51115,7 @@ var ts; } } if (result && errorLocation && meaning & 111551 /* SymbolFlags.Value */ && result.flags & 2097152 /* SymbolFlags.Alias */ && !(result.flags & 111551 /* SymbolFlags.Value */) && !ts.isValidTypeOnlyAliasUseSite(errorLocation)) { - var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); + var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551 /* SymbolFlags.Value */); if (typeOnlyDeclaration) { var message = typeOnlyDeclaration.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type @@ -51198,7 +51278,7 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { + if (meaning & 111551 /* SymbolFlags.Value */) { if (isPrimitiveTypeName(name)) { if (isExtendedByInterface(errorLocation)) { error(errorLocation, ts.Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, ts.unescapeLeadingUnderscores(name)); @@ -51209,7 +51289,8 @@ var ts; return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); - if (symbol && !(symbol.flags & 1024 /* SymbolFlags.NamespaceModule */)) { + var allFlags = symbol && getAllSymbolFlags(symbol); + if (symbol && allFlags !== undefined && !(allFlags & 111551 /* SymbolFlags.Value */)) { var rawName = ts.unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName); @@ -51257,16 +51338,16 @@ var ts; } return false; } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~788968 /* SymbolFlags.Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) { + if (meaning & (111551 /* SymbolFlags.Value */ & ~788968 /* SymbolFlags.Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (788968 /* SymbolFlags.Type */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* SymbolFlags.ValueModule */ | 1024 /* SymbolFlags.NamespaceModule */) & ~788968 /* SymbolFlags.Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1536 /* SymbolFlags.Module */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -51856,6 +51937,52 @@ var ts; } return undefined; } + /** + * Gets combined flags of a `symbol` and all alias targets it resolves to. `resolveAlias` + * is typically recursive over chains of aliases, but stops mid-chain if an alias is merged + * with another exported symbol, e.g. + * ```ts + * // a.ts + * export const a = 0; + * // b.ts + * export { a } from "./a"; + * export type a = number; + * // c.ts + * import { a } from "./b"; + * ``` + * Calling `resolveAlias` on the `a` in c.ts would stop at the merged symbol exported + * from b.ts, even though there is still more alias to resolve. Consequently, if we were + * trying to determine if the `a` in c.ts has a value meaning, looking at the flags on + * the local symbol and on the symbol returned by `resolveAlias` is not enough. + * @returns SymbolFlags.All if `symbol` is an alias that ultimately resolves to `unknown`; + * combined flags of all alias targets otherwise. + */ + function getAllSymbolFlags(symbol) { + var flags = symbol.flags; + var seenSymbols; + while (symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return 67108863 /* SymbolFlags.All */; + } + // Optimizations - try to avoid creating or adding to + // `seenSymbols` if possible + if (target === symbol || (seenSymbols === null || seenSymbols === void 0 ? void 0 : seenSymbols.has(target))) { + break; + } + if (target.flags & 2097152 /* SymbolFlags.Alias */) { + if (seenSymbols) { + seenSymbols.add(target); + } + else { + seenSymbols = new ts.Set([symbol, target]); + } + } + flags |= target.flags; + symbol = target; + } + return flags; + } /** * Marks a symbol as type-only if its declaration is syntactically type-only. * If it is not itself marked type-only, but resolves to a type-only alias @@ -51901,19 +52028,25 @@ var ts; return !!aliasDeclarationLinks.typeOnlyDeclaration; } /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */ - function getTypeOnlyAliasDeclaration(symbol) { + function getTypeOnlyAliasDeclaration(symbol, include) { if (!(symbol.flags & 2097152 /* SymbolFlags.Alias */)) { return undefined; } var links = getSymbolLinks(symbol); - return links.typeOnlyDeclaration || undefined; + if (include === undefined) { + return links.typeOnlyDeclaration || undefined; + } + if (links.typeOnlyDeclaration) { + return getAllSymbolFlags(resolveAlias(links.typeOnlyDeclaration.symbol)) & include ? links.typeOnlyDeclaration : undefined; + } + return undefined; } function markExportAsReferenced(node) { var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol)); + ((getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -51933,8 +52066,7 @@ var ts; // This way a chain of imports can be elided if ultimately the final input is only used in a type // position. if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveSymbol(symbol); - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* SymbolFlags.Value */) { // import foo = checkExpressionCached(node.moduleReference); } @@ -52756,7 +52888,7 @@ var ts; } function symbolIsValue(symbol, includeTypeOnlyMembers) { return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || - symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + symbol.flags & 2097152 /* SymbolFlags.Alias */ && getAllSymbolFlags(symbol) & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -53025,8 +53157,10 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { + var shouldResolveAlias = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)); + symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + var flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + if (flags & meaning) { qualify = true; return true; } @@ -55338,7 +55472,7 @@ var ts; // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it var indices = ts.indicesOf(statements); var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); }); - if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) { + if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return ts.canHaveExportModifier(statements[i]); })) { for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) { var index_1 = associatedIndices_1[_i]; statements[index_1] = addExportModifier(statements[index_1]); @@ -55372,15 +55506,6 @@ var ts; } return statements; } - function canHaveExportModifier(node) { - return ts.isEnumDeclaration(node) || - ts.isVariableStatement(node) || - ts.isFunctionDeclaration(node) || - ts.isClassDeclaration(node) || - (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) || - ts.isInterfaceDeclaration(node) || - isTypeDeclaration(node); - } function addExportModifier(node) { var flags = (ts.getEffectiveModifierFlags(node) | 1 /* ModifierFlags.Export */) & ~2 /* ModifierFlags.Ambient */; return ts.factory.updateModifiers(node, flags); @@ -55627,7 +55752,7 @@ var ts; (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* ModifierFlags.Export */ && enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && - canHaveExportModifier(node)) { + ts.canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* ModifierFlags.Export */; } @@ -55683,7 +55808,7 @@ var ts; return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { - return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* SymbolFlags.Value */); }); + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* SymbolFlags.Value */); }); } function serializeModule(symbol, symbolName, modifierFlags) { var members = getNamespaceMembersForSerialization(symbol); @@ -57903,7 +58028,7 @@ var ts; links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType - : targetSymbol.flags & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) + : getAllSymbolFlags(targetSymbol) & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; @@ -59786,7 +59911,20 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ && getMappedTypeModifiers(type) & 4 /* MappedTypeModifiers.IncludeOptional */); } function isGenericMappedType(type) { - return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + if (ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) { + var constraint = getConstraintTypeFromMappedType(type); + if (isGenericIndexType(constraint)) { + return true; + } + // A mapped type is generic if the 'as' clause references generic types other than the iteration type. + // To determine this, we substitute the constraint type (that we now know isn't generic) for the iteration + // type and check whether the resulting type is generic. + var nameType = getNameTypeFromMappedType(type); + if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) { + return true; + } + } + return false; } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -60256,7 +60394,7 @@ var ts; var indexTypes; var isUnion = containingType.flags & 1048576 /* TypeFlags.Union */; // Flags we want to propagate to the result if they exist in all source symbols - var optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */; + var optionalFlag; var syntheticFlag = 4 /* CheckFlags.SyntheticMethod */; var checkFlags = isUnion ? 0 : 8 /* CheckFlags.Readonly */; var mergedInstantiations = false; @@ -60267,11 +60405,14 @@ var ts; var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop) { - if (isUnion) { - optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); - } - else { - optionalFlag &= prop.flags; + if (prop.flags & 106500 /* SymbolFlags.ClassMember */) { + optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : (optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */); + if (isUnion) { + optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); + } + else { + optionalFlag &= prop.flags; + } } if (!singleProp) { singleProp = prop; @@ -60390,7 +60531,7 @@ var ts; propTypes.push(type); } ts.addRange(propTypes, indexTypes); - var result = createSymbol(4 /* SymbolFlags.Property */ | optionalFlag, name, syntheticFlag | checkFlags); + var result = createSymbol(4 /* SymbolFlags.Property */ | (optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : 0), name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && firstValueDeclaration) { result.valueDeclaration = firstValueDeclaration; @@ -63103,8 +63244,14 @@ var ts; return getStringLiteralType(text); } newTexts.push(text); - if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { - return stringType; + if (ts.every(newTexts, function (t) { return t === ""; })) { + if (ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { + return stringType; + } + // Normalize `${Mapping}` into Mapping + if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) { + return newTypes[0]; + } } var id = "".concat(getTypeListId(newTypes), "|").concat(ts.map(newTexts, function (t) { return t.length; }).join(","), "|").concat(newTexts.join("")); var type = templateLiteralTypes.get(id); @@ -63163,12 +63310,14 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - // Mapping> === Mapping - type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : - isGenericIndexType(type) || isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, isPatternLiteralPlaceholderType(type) && !(type.flags & 268435456 /* TypeFlags.StringMapping */) ? getTemplateLiteralType(["", ""], [type]) : type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : - type; + type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : + type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : + // Mapping> === Mapping + type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : + type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : + // This handles Mapping<`${number}`> and Mapping<`${bigint}`> + isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : + type; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -63333,7 +63482,18 @@ var ts; return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; } errorIfWritingToReadonlyIndex(indexInfo); - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; + // When accessing an enum object with its own type, + // e.g. E[E.A] for enum E { A }, undefined shouldn't + // be included in the result type + if ((accessFlags & 1 /* AccessFlags.IncludeUndefined */) && + !(objectType.symbol && + objectType.symbol.flags & (256 /* SymbolFlags.RegularEnum */ | 128 /* SymbolFlags.ConstEnum */) && + (indexType.symbol && + indexType.flags & 1024 /* TypeFlags.EnumLiteral */ && + getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + return getUnionType([indexInfo.type, undefinedType]); + } + return indexInfo.type; } if (indexType.flags & 131072 /* TypeFlags.Never */) { return neverType; @@ -63436,10 +63596,11 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || isPatternLiteralType(type); } function isPatternLiteralType(type) { - return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); + return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType) || + !!(type.flags & 268435456 /* TypeFlags.StringMapping */) && isPatternLiteralPlaceholderType(type.type); } function isGenericType(type) { return !!getGenericObjectFlags(type); @@ -63718,18 +63879,23 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_20 = function () { + // We loop here for an immediately nested conditional type in the false position, effectively treating + // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for + // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of + // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive + // cases we increment the tail recursion counter and stop after 1000 iterations. + while (true) { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; - return "break"; + break; } var isUnwrapped = isTypicalNondistributiveConditional(root); var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { - return { value: wildcardType }; + return wildcardType; } var combinedMapper = void 0; if (root.inferTypeParameters) { @@ -63762,11 +63928,7 @@ var ts; } } } - // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type - // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to - // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint - // so in those cases we refain from performing inference and retain the uninfered type parameter - if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -63798,14 +63960,14 @@ var ts; var newRoot = falseType_1.root; if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) { root = newRoot; - return "continue"; + continue; } if (canTailRecurse(falseType_1, mapper)) { - return "continue"; + continue; } } result = instantiateType(falseType_1, mapper); - return "break"; + break; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -63816,10 +63978,10 @@ var ts; var trueType_1 = getTypeFromTypeNode(root.node.trueType); var trueMapper = combinedMapper || mapper; if (canTailRecurse(trueType_1, trueMapper)) { - return "continue"; + continue; } result = instantiateType(trueType_1, trueMapper); - return "break"; + break; } } // Return a deferred type for a check that is neither definitely true nor definitely false @@ -63831,19 +63993,7 @@ var ts; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 - return "break"; - }; - // We loop here for an immediately nested conditional type in the false position, effectively treating - // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for - // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of - // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive - // cases we increment the tail recursion counter and stop after 1000 iterations. - while (true) { - var state_6 = _loop_20(); - if (typeof state_6 === "object") - return state_6.value; - if (state_6 === "break") - break; + break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; // We tail-recurse for generic conditional types that (a) have not already been evaluated and cached, and @@ -66297,7 +66447,7 @@ var ts; return 0 /* Ternary.False */; } } - var isPerformingCommonPropertyChecks = (relation !== comparableRelation || !(source.flags & 1048576 /* TypeFlags.Union */) && isLiteralType(source)) && + var isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source)) && !(intersectionState & 2 /* IntersectionState.Target */) && source.flags & (131068 /* TypeFlags.Primitive */ | 524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && source !== globalObjectType && target.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && isWeakType(target) && @@ -66325,27 +66475,6 @@ var ts; var result_7 = skipCaching ? unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) : recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags); - // For certain combinations involving intersections and optional, excess, or mismatched properties we need - // an extra property check where the intersection is viewed as a single object. The following are motivating - // examples that all should be errors, but aren't without this extra property check: - // - // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property - // - // declare let wrong: { a: { y: string } }; - // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type - // - // function foo(x: { a?: string }, y: T & { a: boolean }) { - // x = y; // Mismatched property in source intersection - // } - // - // We suppress recursive intersection property checks because they can generate lots of work when relating - // recursive intersections that are structurally similar but not exactly identical. See #37854. - if (result_7 && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { - inPropertyCheck = true; - result_7 &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* IntersectionState.PropertyCheck */, recursionFlags); - inPropertyCheck = false; - } if (result_7) { return result_7; } @@ -66457,7 +66586,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_21 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -66520,9 +66649,9 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_7 = _loop_21(prop); - if (typeof state_7 === "object") - return state_7.value; + var state_6 = _loop_20(prop); + if (typeof state_6 === "object") + return state_6.value; } return false; } @@ -66743,8 +66872,7 @@ var ts; if (overflow) { return 0 /* Ternary.False */; } - var keyIntersectionState = intersectionState | (inPropertyCheck ? 8 /* IntersectionState.InPropertyCheck */ : 0); - var id = getRelationKey(source, target, keyIntersectionState, relation, /*ingnoreConstraints*/ false); + var id = getRelationKey(source, target, intersectionState, relation, /*ingnoreConstraints*/ false); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* RelationComparisonResult.Failed */ && !(entry & 4 /* RelationComparisonResult.Reported */)) { @@ -66774,7 +66902,7 @@ var ts; // A key that starts with "*" is an indication that we have type references that reference constrained // type parameters. For such keys we also check against the key we would have gotten if all type parameters // were unconstrained. - var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, keyIntersectionState, relation, /*ignoreConstraints*/ true) : undefined; + var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, intersectionState, relation, /*ignoreConstraints*/ true) : undefined; for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { @@ -66861,7 +66989,7 @@ var ts; function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { var saveErrorInfo = captureErrorCalculationState(); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo); - if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + if (relation !== identityRelation) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -66875,10 +67003,33 @@ var ts; // needs to have its constraint hoisted into an intersection with said type parameter, this way // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` - var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); - if (constraint && !(constraint.flags & 131072 /* TypeFlags.Never */) && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself - // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this - result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); + if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself + // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this + result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + } + } + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && !isGenericObjectType(target) && source.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) || + isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { + inPropertyCheck = true; + result &= propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); + inPropertyCheck = false; } } if (result) { @@ -66887,9 +67038,6 @@ var ts; return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo) { - if (intersectionState & 4 /* IntersectionState.PropertyCheck */) { - return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); - } var result; var originalErrorInfo; var varianceCheckFailed = false; @@ -66990,7 +67138,7 @@ var ts; // with another type parameter unless one extends the other. (Remember: comparability is mostly bidirectional!) var constraint = getConstraintOfTypeParameter(source); if (constraint && hasNonCircularBaseConstraint(source)) { - while (constraint && constraint.flags & 262144 /* TypeFlags.TypeParameter */) { + while (constraint && someType(constraint, function (c) { return !!(c.flags & 262144 /* TypeFlags.TypeParameter */); })) { if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { return result; } @@ -67513,11 +67661,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_22 = function (combination) { + var _loop_21 = function (combination) { var hasMatch = false; outer: for (var _c = 0, _d = target.types; _c < _d.length; _c++) { var type = _d[_c]; - var _loop_23 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -67533,8 +67681,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_9 = _loop_23(i); - switch (state_9) { + var state_8 = _loop_22(i); + switch (state_8) { case "continue-outer": continue outer; } } @@ -67547,9 +67695,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_8 = _loop_22(combination); - if (typeof state_8 === "object") - return state_8.value; + var state_7 = _loop_21(combination); + if (typeof state_7 === "object") + return state_7.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* Ternary.True */; @@ -67646,7 +67794,7 @@ var ts; return 0 /* Ternary.False */; } // When checking for comparability, be more lenient with optional properties. - if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && targetProp.flags & 106500 /* SymbolFlags.ClassMember */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -68254,7 +68402,7 @@ var ts; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); links.variances = ts.emptyArray; var variances = []; - var _loop_24 = function (tp) { + var _loop_23 = function (tp) { var modifiers = getVarianceModifiers(tp); var variance = modifiers & 65536 /* ModifierFlags.Out */ ? modifiers & 32768 /* ModifierFlags.In */ ? 0 /* VarianceFlags.Invariant */ : 1 /* VarianceFlags.Covariant */ : @@ -68292,7 +68440,7 @@ var ts; }; for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var tp = typeParameters_2[_i]; - _loop_24(tp); + _loop_23(tp); } links.variances = variances; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); @@ -68746,8 +68894,7 @@ var ts; return !!(type.flags & 109440 /* TypeFlags.Unit */); } function isUnitLikeType(type) { - return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.some(type.types, isUnitType) : - !!(type.flags & 109440 /* TypeFlags.Unit */); + return isUnitType(getBaseConstraintOrType(type)); } function extractUnitType(type) { return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.find(type.types, isUnitType) || type : type; @@ -69626,7 +69773,7 @@ var ts; && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); } function isMemberOfStringMapping(source, target) { - if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + if (target.flags & (4 /* TypeFlags.String */ | 1 /* TypeFlags.Any */)) { return true; } if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { @@ -70250,7 +70397,7 @@ var ts; // upon instantiation, would collapse all the placeholders to just 'string', and an assignment check might // succeed. That would be a pointless and confusing outcome. if (matches || ts.every(target.texts, function (s) { return s.length === 0; })) { - var _loop_25 = function (i) { + var _loop_24 = function (i) { var source_1 = matches ? matches[i] : neverType; var target_3 = types[i]; // If we are inferring from a string literal type to a type variable whose constraint includes one of the @@ -70300,7 +70447,7 @@ var ts; inferFromTypes(source_1, target_3); }; for (var i = 0; i < types.length; i++) { - _loop_25(i); + _loop_24(i); } } } @@ -70752,7 +70899,7 @@ var ts; } if (ts.isEntityNameExpression(node.argumentExpression)) { var symbol = resolveEntityName(node.argumentExpression, 111551 /* SymbolFlags.Value */, /*ignoreErrors*/ true); - if (!symbol || !isConstVariable(symbol)) + if (!symbol || !(isConstVariable(symbol) || (symbol.flags & 8 /* SymbolFlags.EnumMember */))) return undefined; var declaration = symbol.valueDeclaration; if (declaration === undefined) @@ -70766,7 +70913,12 @@ var ts; } if (ts.hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node.argumentExpression)) { var initializer = ts.getEffectiveInitializer(declaration); - return initializer && tryGetNameFromType(getTypeOfExpression(initializer)); + if (initializer) { + return tryGetNameFromType(getTypeOfExpression(initializer)); + } + if (ts.isEnumMember(declaration)) { + return ts.getTextOfPropertyName(declaration.name); + } } } return undefined; @@ -70824,7 +70976,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_26 = function (type) { + var _loop_25 = function (type) { if (type.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */ | 58982400 /* TypeFlags.InstantiableNonPrimitive */)) { var discriminant = getTypeOfPropertyOfType(type, name); if (discriminant) { @@ -70850,9 +71002,9 @@ var ts; }; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var type = types_15[_i]; - var state_10 = _loop_26(type); - if (typeof state_10 === "object") - return state_10.value; + var state_9 = _loop_25(type); + if (typeof state_9 === "object") + return state_9.value; } return count >= 10 && count * 2 >= types.length ? map : undefined; } @@ -71449,6 +71601,7 @@ var ts; ts.isInJSFile(node) && ts.hasInitializer(node) && node.initializer && ts.isFunctionExpressionOrArrowFunction(node.initializer) && ts.getEffectiveReturnTypeNode(node.initializer)); } function getExplicitTypeOfSymbol(symbol, diagnostic) { + symbol = resolveSymbol(symbol); if (symbol.flags & (16 /* SymbolFlags.Function */ | 8192 /* SymbolFlags.Method */ | 32 /* SymbolFlags.Class */ | 512 /* SymbolFlags.ValueModule */)) { return getTypeOfSymbol(symbol); } @@ -71487,7 +71640,7 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); - return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol, diagnostic); + return getExplicitTypeOfSymbol(symbol, diagnostic); case 108 /* SyntaxKind.ThisKeyword */: return getExplicitThisType(node); case 106 /* SyntaxKind.SuperKeyword */: @@ -71974,7 +72127,7 @@ var ts; type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (expr.kind === 218 /* SyntaxKind.TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { - type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { if (strictNullChecks) { @@ -72255,7 +72408,7 @@ var ts; !!(prop.flags & 16777216 /* SymbolFlags.Optional */) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue; } - function narrowByInKeyword(type, nameType, assumeTrue) { + function narrowTypeByInKeyword(type, nameType, assumeTrue) { var name = getPropertyNameFromType(nameType); var isKnownProperty = someType(type, function (t) { return isTypePresencePossible(t, name, /*assumeTrue*/ true); }); if (isKnownProperty) { @@ -72336,7 +72489,7 @@ var ts; return getTypeWithFacts(type, assumeTrue ? 524288 /* TypeFacts.NEUndefined */ : 65536 /* TypeFacts.EQUndefined */); } if (isMatchingReference(reference, target)) { - return narrowByInKeyword(type, leftType, assumeTrue); + return narrowTypeByInKeyword(type, leftType, assumeTrue); } } break; @@ -72525,7 +72678,7 @@ var ts; neverType; }); } - function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + function narrowTypeBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!witnesses) { return type; @@ -72913,15 +73066,15 @@ var ts; }); } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { var target = resolveAlias(symbol); - if (target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */)) { // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled // (because the const enum value will not be inlined), or if (2) the alias is an export // of a const enum declaration that will be preserved. if (compilerOptions.isolatedModules || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || - !isConstEnumOrConstEnumOnlyModule(target)) { + !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -73149,7 +73302,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 16384 /* TypeFlags.Void */)) !== 0 || isInTypeQuery(node) || node.parent.kind === 278 /* SyntaxKind.ExportSpecifier */) || node.parent.kind === 232 /* SyntaxKind.NonNullExpression */ || @@ -73178,6 +73331,12 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function isSameScopedBindingElement(node, declaration) { + if (ts.isBindingElement(declaration)) { + var bindingElement = ts.findAncestor(node, ts.isBindingElement); + return bindingElement && ts.getRootDeclaration(bindingElement) === ts.getRootDeclaration(declaration); + } + } function shouldMarkIdentifierAliasReferenced(node) { var _a; var parent = node.parent; @@ -73519,12 +73678,17 @@ var ts; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; + var inAsyncFunction = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { while (container && container.kind === 216 /* SyntaxKind.ArrowFunction */) { + if (ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ScriptTarget.ES2015 */; } + if (container && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; @@ -73630,12 +73794,12 @@ var ts; // as a call expression cannot be used as the target of a destructuring assignment while a property access can. // // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. - if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) { + if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && inAsyncFunction) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */; + getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */; } else { - getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.AsyncMethodWithSuper */; + getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */; } } if (needToCaptureLexicalThis) { @@ -74331,9 +74495,10 @@ var ts; function instantiateContextualType(contextualType, node, contextFlags) { if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* TypeFlags.Instantiable */)) { var inferenceContext = getInferenceContext(node); - // If no inferences have been made, nothing is gained from instantiating as type parameters - // would just be replaced with their defaults similar to the apparent type. - if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + // If no inferences have been made, and none of the type parameters for which we are inferring + // specify default types, nothing is gained from instantiating as type parameters would just be + // replaced with their constraints similar to the apparent type. + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) { // For contextual signatures we incorporate all inferences made so far, e.g. from return // types as well as arguments to the left in a function call. return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); @@ -77307,7 +77472,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_27 = function (i) { + var _loop_26 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. var spreadType = arg.kind === 227 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -77324,7 +77489,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_27(i); + _loop_26(i); } return effectiveArgs_1; } @@ -77653,7 +77818,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_28 = function (c) { + var _loop_27 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* CheckMode.Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -77671,7 +77836,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_28(c); + _loop_27(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -77829,7 +77994,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_29 = function (i) { + var _loop_28 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -77837,7 +78002,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_29(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -78807,7 +78972,7 @@ var ts; if (symbol && symbol.flags & 2097152 /* SymbolFlags.Alias */) { symbol = resolveAlias(symbol); } - return !!(symbol && (symbol.flags & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); + return !!(symbol && (getAllSymbolFlags(symbol) & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); } return false; } @@ -79469,7 +79634,17 @@ var ts; } function isExhaustiveSwitchStatement(node) { var links = getNodeLinks(node); - return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); + if (links.isExhaustive === undefined) { + links.isExhaustive = 0; // Indicate resolution is in process + var exhaustive = computeExhaustiveSwitchStatement(node); + if (links.isExhaustive === 0) { + links.isExhaustive = exhaustive; + } + } + else if (links.isExhaustive === 0) { + links.isExhaustive = false; // Resolve circularity to false + } + return links.isExhaustive; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 218 /* SyntaxKind.TypeOfExpression */) { @@ -79477,7 +79652,7 @@ var ts; if (!witnesses) { return false; } - var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(node.expression.expression)); + var operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression)); // Get the not-equal flags for all handled cases. var notEqualFacts_2 = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); if (operandConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */) { @@ -79487,7 +79662,7 @@ var ts; // A missing not-equal flag indicates that the type wasn't handled by some case. return !someType(operandConstraint, function (t) { return (getTypeFacts(t) & notEqualFacts_2) === notEqualFacts_2; }); } - var type = getTypeOfExpression(node.expression); + var type = checkExpressionCached(node.expression); if (!isLiteralType(type)) { return false; } @@ -81181,6 +81356,9 @@ var ts; function hasInferenceCandidates(info) { return !!(info.candidates || info.contraCandidates); } + function hasInferenceCandidatesOrDefault(info) { + return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter)); + } function hasOverlappingInferences(a, b) { for (var i = 0; i < a.length; i++) { if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) { @@ -81882,7 +82060,7 @@ var ts; var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var indexSignatureMap_1 = new ts.Map(); - var _loop_30 = function (declaration) { + var _loop_29 = function (declaration) { if (declaration.parameters.length === 1 && declaration.parameters[0].type) { forEachType(getTypeFromTypeNode(declaration.parameters[0].type), function (type) { var entry = indexSignatureMap_1.get(getTypeId(type)); @@ -81897,7 +82075,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_30(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -82174,7 +82352,7 @@ var ts; } var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { - if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { + if (ts.some(symbol.declarations, function (d) { return ts.isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* TypeFlags.Enum */ && symbol.flags & 8 /* SymbolFlags.EnumMember */) { @@ -82777,7 +82955,7 @@ var ts; return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; } // primitives with a `{ then() }` won't be unwrapped/adopted. - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217 @@ -82844,7 +83022,7 @@ var ts; * Determines whether a type is an object with a callable `then` member. */ function isThenableType(type) { - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { // primitive types cannot be considered "thenable" since they are not objects. return false; } @@ -82878,7 +83056,7 @@ var ts; // We only need `Awaited` if `T` is a type variable that has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`, // or is promise-like. if (baseConstraint ? - baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint) : + baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { return true; } @@ -83552,7 +83730,7 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + var message = ts.isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(declaration, 0 /* UnusedKind.Local */, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { @@ -84982,7 +85160,16 @@ var ts; var message = allowAsyncIterables ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; - return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + var suggestAwait = + // for (const x of Promise<...>) or [...Promise<...>] + !!getAwaitedTypeOfPromise(type) + // for (const x of AsyncIterable<...>) + || (!allowAsyncIterables && + ts.isForOfStatement(errorNode.parent) && + errorNode.parent.expression === errorNode && + getGlobalAsyncIterableType(/** reportErrors */ false) !== emptyGenericType && + isTypeAssignableTo(type, getGlobalAsyncIterableType(/** reportErrors */ false))); + return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. @@ -85497,7 +85684,7 @@ var ts; var propDeclaration = declaration && declaration.kind === 223 /* SyntaxKind.BinaryExpression */ || name && name.kind === 164 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_31 = function (info) { + var _loop_30 = function (info) { var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; // We check only when (a) the property is declared in the containing type, or (b) the applicable index signature is declared // in the containing type, or (c) the containing type is an interface and no base interface contains both the property and @@ -85514,7 +85701,7 @@ var ts; }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_31(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -85522,7 +85709,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 261 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_32 = function (info) { + var _loop_31 = function (info) { if (info === checkInfo) return "continue"; var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; @@ -85537,7 +85724,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_32(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -85592,7 +85779,7 @@ var ts; } else { ts.forEach(jsdocParameters, function (_a, index) { - var name = _a.name; + var name = _a.name, isNameFirst = _a.isNameFirst; if (excludedParameters.has(index) || ts.isIdentifier(name) && parameters.has(name.escapedText)) { return; } @@ -85602,7 +85789,9 @@ var ts; } } else { - errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + if (!isNameFirst) { + errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + } } }); } @@ -85857,7 +86046,7 @@ var ts; 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 _loop_33 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -85874,7 +86063,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_33(member); + _loop_32(member); } } /** @@ -85962,7 +86151,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_34 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -85981,7 +86170,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_34(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -86052,7 +86241,7 @@ var ts; var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - var _loop_35 = function (baseProperty) { + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { return "continue"; @@ -86162,8 +86351,8 @@ var ts; }; basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { var baseProperty = baseProperties_1[_i]; - var state_11 = _loop_35(baseProperty); - switch (state_11) { + var state_10 = _loop_34(baseProperty); + switch (state_10) { case "continue-basePropertyCheck": continue basePropertyCheck; } } @@ -86682,12 +86871,11 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { - var _a; switch (node.kind) { case 240 /* SyntaxKind.VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { - var decl = _b[_i]; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; @@ -86703,8 +86891,8 @@ var ts; case 257 /* SyntaxKind.VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { - var el = _d[_c]; + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -86720,18 +86908,6 @@ var ts; if (isGlobalAugmentation) { return; } - var symbol = getSymbolOfNode(node); - if (symbol) { - // module augmentations cannot introduce new names on the top level scope of the module - // this is done it two steps - // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error - // 2. main check - report error if value declaration of the parent symbol is module augmentation) - var reportError = !(symbol.flags & 33554432 /* SymbolFlags.Transient */); - if (!reportError) { - // symbol should not originate in augmentation - reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } break; } } @@ -86833,10 +87009,11 @@ var ts; } return; } + var targetFlags = getAllSymbolFlags(target); var excludedMeanings = (symbol.flags & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */) ? 111551 /* SymbolFlags.Value */ : 0) | (symbol.flags & 788968 /* SymbolFlags.Type */ ? 788968 /* SymbolFlags.Type */ : 0) | (symbol.flags & 1920 /* SymbolFlags.Namespace */ ? 1920 /* SymbolFlags.Namespace */ : 0); - if (target.flags & excludedMeanings) { + if (targetFlags & excludedMeanings) { var message = node.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; @@ -86846,7 +87023,7 @@ var ts; && !ts.isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 16777216 /* NodeFlags.Ambient */)) { var typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol); - var isType = !(target.flags & 111551 /* SymbolFlags.Value */); + var isType = !(targetFlags & 111551 /* SymbolFlags.Value */); if (isType || typeOnlyAlias) { switch (node.kind) { case 270 /* SyntaxKind.ImportClause */: @@ -87006,14 +87183,15 @@ var ts; if (node.moduleReference.kind !== 280 /* SyntaxKind.ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 111551 /* SymbolFlags.Value */) { + var targetFlags = getAllSymbolFlags(target); + if (targetFlags & 111551 /* SymbolFlags.Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* SymbolFlags.Value */ | 1920 /* SymbolFlags.Namespace */).flags & 1920 /* SymbolFlags.Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 788968 /* SymbolFlags.Type */) { + if (targetFlags & 788968 /* SymbolFlags.Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -87152,7 +87330,7 @@ var ts; markExportAsReferenced(node); } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); - if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (!target || getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); } } @@ -87199,7 +87377,7 @@ var ts; markAliasReferenced(sym, id); // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`) var target = sym.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(sym) : sym; - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { // However if it is a value, we need to check it's being used correctly checkExpressionCached(node.expression); } @@ -87871,29 +88049,9 @@ var ts; } function isTypeDeclarationName(name) { return name.kind === 79 /* SyntaxKind.Identifier */ && - isTypeDeclaration(name.parent) && + ts.isTypeDeclaration(name.parent) && ts.getNameOfDeclaration(name.parent) === name; } - function isTypeDeclaration(node) { - switch (node.kind) { - case 165 /* SyntaxKind.TypeParameter */: - case 260 /* SyntaxKind.ClassDeclaration */: - case 261 /* SyntaxKind.InterfaceDeclaration */: - case 262 /* SyntaxKind.TypeAliasDeclaration */: - case 263 /* SyntaxKind.EnumDeclaration */: - case 348 /* SyntaxKind.JSDocTypedefTag */: - case 341 /* SyntaxKind.JSDocCallbackTag */: - case 342 /* SyntaxKind.JSDocEnumTag */: - return true; - case 270 /* SyntaxKind.ImportClause */: - return node.isTypeOnly; - case 273 /* SyntaxKind.ImportSpecifier */: - case 278 /* SyntaxKind.ExportSpecifier */: - return node.parent.parent.isTypeOnly; - default: - return false; - } - } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { while (node.parent.kind === 163 /* SyntaxKind.QualifiedName */) { @@ -88326,7 +88484,7 @@ var ts; var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } - if (isTypeDeclaration(node)) { + if (ts.isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration var symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); @@ -88521,7 +88679,7 @@ var ts; return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 111551 /* SymbolFlags.Value */); + return s && !!(getAllSymbolFlags(s) & 111551 /* SymbolFlags.Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -88574,7 +88732,7 @@ var ts; var symbol = getReferencedValueOrAliasSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -88662,7 +88820,7 @@ var ts; case 273 /* SyntaxKind.ImportSpecifier */: case 278 /* SyntaxKind.ExportSpecifier */: var symbol = getSymbolOfNode(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); + return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */); case 275 /* SyntaxKind.ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || @@ -88684,6 +88842,7 @@ var ts; return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); } function isAliasResolvedToValue(symbol) { + var _a; if (!symbol) { return false; } @@ -88693,7 +88852,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 111551 /* SymbolFlags.Value */) && + return !!(((_a = getAllSymbolFlags(target)) !== null && _a !== void 0 ? _a : -1) & 111551 /* SymbolFlags.Value */) && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -88708,7 +88867,7 @@ var ts; } var target = getSymbolLinks(symbol).aliasTarget; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* ModifierFlags.Export */ && - target.flags & 111551 /* SymbolFlags.Value */ && + getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */ && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; @@ -98362,8 +98521,11 @@ var ts; } return ts.visitEachChild(node, visitor, context); case 174 /* SyntaxKind.GetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitGetAccessorDeclaration, node); case 175 /* SyntaxKind.SetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitSetAccessorDeclaration, node); case 173 /* SyntaxKind.Constructor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitConstructorDeclaration, node); case 260 /* SyntaxKind.ClassDeclaration */: case 228 /* SyntaxKind.ClassExpression */: return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitDefault, node); @@ -98464,6 +98626,9 @@ var ts; return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression( /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); + } /** * Visits a MethodDeclaration node. * @@ -98478,7 +98643,14 @@ var ts; /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) - : ts.visitFunctionBody(node.body, visitor, context)); + : transformMethodBody(node)); + } + function visitGetAccessorDeclaration(node) { + return factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformMethodBody(node)); + } + function visitSetAccessorDeclaration(node) { + return factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); } /** * Visits a FunctionDeclaration node. @@ -98592,6 +98764,42 @@ var ts; } return false; } + function transformMethodBody(node) { + ts.Debug.assertIsDefined(node.body); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = new ts.Set(); + hasSuperElementAccess = false; + var updated = ts.visitFunctionBody(node.body, visitor, context); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var originalMethod = ts.getOriginalNode(node, ts.isFunctionLikeDeclaration); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && + resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) && + (ts.getFunctionFlags(originalMethod) & 3 /* FunctionFlags.AsyncGenerator */) !== 3 /* FunctionFlags.AsyncGenerator */; + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + if (capturedSuperProperties.size) { + var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + var statements = updated.statements.slice(); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + updated = factory.updateBlock(updated, statements); + } + if (hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { + ts.addEmitHelper(updated, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { + ts.addEmitHelper(updated, ts.asyncSuperHelper); + } + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return updated; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -98624,7 +98832,7 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { @@ -98637,10 +98845,10 @@ var ts; ts.setTextRange(block, node.body); if (emitSuperHelpers && hasSuperElementAccess) { // Emit helpers for super element access expressions (`super[x]`). - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -98712,7 +98920,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ES2017SubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -98789,7 +98997,7 @@ var ts; || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -98804,7 +99012,7 @@ var ts; function createSuperAccessVariableStatement(factory, resolver, node, names) { // Create a variable declaration with a getter/setter (if binding) definition for each name: // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); - var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) !== 0; + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) !== 0; var accessors = []; names.forEach(function (_, key) { var name = ts.unescapeLeadingUnderscores(key); @@ -99297,11 +99505,22 @@ var ts; } return node; } - function convertForOfStatementHead(node, boundValue) { - var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue); + function convertForOfStatementHead(node, boundValue, nonUserCode) { + var value = factory.createTempVariable(hoistVariableDeclaration); + var iteratorValueExpression = factory.createAssignment(value, boundValue); + var iteratorValueStatement = factory.createExpressionStatement(iteratorValueExpression); + ts.setSourceMapRange(iteratorValueStatement, node.expression); + var exitNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createFalse()); + var exitNonUserCodeStatement = factory.createExpressionStatement(exitNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var enterNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createTrue()); + var enterNonUserCodeStatement = factory.createExpressionStatement(enterNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var statements = []; + var binding = ts.createForOfBindingStatement(factory, node.initializer, value); + statements.push(ts.visitNode(binding, visitor, ts.isStatement)); var bodyLocation; var statementsLocation; - var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); @@ -99311,8 +99530,16 @@ var ts; else { statements.push(statement); } - return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), + var body = ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* EmitFlags.NoSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */); + return factory.createBlock([ + iteratorValueStatement, + exitNonUserCodeStatement, + factory.createTryStatement(body, + /*catchClause*/ undefined, factory.createBlock([ + enterNonUserCodeStatement + ])) + ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ @@ -99323,6 +99550,8 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined); + var nonUserCode = factory.createTempVariable(/*recordTempVariable*/ undefined); + var done = factory.createTempVariable(hoistVariableDeclaration); var errorRecord = factory.createUniqueName("e"); var catchVariable = factory.getGeneratedNameForNode(errorRecord); var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined); @@ -99339,12 +99568,17 @@ var ts; callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement( /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([ + factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()), ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression), factory.createVariableDeclaration(result) ]), node.expression), 2097152 /* EmitFlags.NoHoisting */), - /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), + /*condition*/ factory.inlineExpressions([ + factory.createAssignment(result, createDownlevelAwait(callNext)), + factory.createAssignment(done, getDone), + factory.createLogicalNot(done) + ]), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, getValue)), + /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode)), /*location*/ node), 256 /* EmitFlags.NoTokenTrailingSourceMaps */); ts.setOriginalNode(forStatement, node); return factory.createTryStatement(factory.createBlock([ @@ -99356,7 +99590,7 @@ var ts; ]), 1 /* EmitFlags.SingleLine */)), factory.createBlock([ factory.createTryStatement( /*tryBlock*/ factory.createBlock([ - ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(getDone)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) + ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(factory.createLogicalNot(nonUserCode), factory.createLogicalNot(done)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([ @@ -99512,7 +99746,7 @@ var ts; /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HierarchyFacts.HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); @@ -99523,10 +99757,10 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = factory.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -99655,7 +99889,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ESNextSubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -99732,7 +99966,7 @@ var ts; || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -101201,11 +101435,13 @@ var ts; return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); } function visitIdentifier(node) { - if (!convertedLoopState) { - return node; + if (convertedLoopState) { + if (resolver.isArgumentsLocalBinding(node)) { + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + } } - if (resolver.isArgumentsLocalBinding(node)) { - return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + if (node.hasExtendedUnicodeEscape) { + return ts.setOriginalNode(ts.setTextRange(factory.createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText)), node), node); } return node; } @@ -105352,7 +105588,6 @@ var ts; return node; } function transformAndEmitForInStatement(node) { - // TODO(rbuckton): Source map locations if (containsYield(node)) { // [source] // for (var p in o) { @@ -105360,34 +105595,41 @@ var ts; // } // // [intermediate] - // .local _a, _b, _i - // _a = []; - // for (_b in o) _a.push(_b); + // .local _b, _a, _c, _i + // _b = []; + // _a = o; + // for (_c in _a) _b.push(_c); // _i = 0; // .loop incrementLabel, endLoopLabel // .mark conditionLabel - // .brfalse endLoopLabel, (_i < _a.length) - // p = _a[_i]; + // .brfalse endLoopLabel, (_i < _b.length) + // _c = _b[_i]; + // .brfalse incrementLabel, (_c in _a) + // p = _c; // /*body*/ // .mark incrementLabel - // _b++; + // _c++; // .br conditionLabel // .endloop // .mark endLoopLabel - var keysArray = declareLocal(); // _a - var key = declareLocal(); // _b + var obj = declareLocal(); // _a + var keysArray = declareLocal(); // _b + var key = declareLocal(); // _c var keysIndex = factory.createLoopVariable(); // _i var initializer = node.initializer; hoistVariableDeclaration(keysIndex); + emitAssignment(obj, ts.visitNode(node.expression, visitor, ts.isExpression)); emitAssignment(keysArray, factory.createArrayLiteralExpression()); - emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), + emitStatement(factory.createForInStatement(key, obj, factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), /*typeArguments*/ undefined, [key])))); emitAssignment(keysIndex, factory.createNumericLiteral(0)); var conditionLabel = defineLabel(); var incrementLabel = defineLabel(); - var endLabel = beginLoopBlock(incrementLabel); + var endLoopLabel = beginLoopBlock(incrementLabel); markLabel(conditionLabel); - emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitBreakWhenFalse(endLoopLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitAssignment(key, factory.createElementAccessExpression(keysArray, keysIndex)); + emitBreakWhenFalse(incrementLabel, factory.createBinaryExpression(key, 101 /* SyntaxKind.InKeyword */, obj)); var variable = void 0; if (ts.isVariableDeclarationList(initializer)) { for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { @@ -105400,7 +105642,7 @@ var ts; variable = ts.visitNode(initializer, visitor, ts.isExpression); ts.Debug.assert(ts.isLeftHandSideExpression(variable)); } - emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex)); + emitAssignment(variable, key); transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex))); @@ -107241,7 +107483,7 @@ var ts; return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return createImportCallExpressionCommonJS(argument, containsLexicalThis); + return createImportCallExpressionCommonJS(argument); } } function createImportCallExpressionUMD(arg, containsLexicalThis) { @@ -107264,7 +107506,7 @@ var ts; return factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(arg), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); } @@ -107273,7 +107515,7 @@ var ts; return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, /* isInlineable */ true), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); } @@ -107323,14 +107565,20 @@ var ts; } return promise; } - function createImportCallExpressionCommonJS(arg, containsLexicalThis) { - // import("./blah") + function createImportCallExpressionCommonJS(arg, isInlineable) { + // import(x) // emit as - // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // var _a; + // (_a = x, Promise.resolve().then(() => require(_a)) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); - var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + // If the arg is not inlineable, we have to evaluate it in the current scope with a temp var + var temp = arg && !ts.isSimpleInlineableExpression(arg) && !isInlineable ? factory.createTempVariable(hoistVariableDeclaration) : undefined; + var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), + /*typeArguments*/ undefined, + /*argumentsArray*/ []); + var requireCall = factory.createCallExpression(factory.createIdentifier("require"), + /*typeArguments*/ undefined, temp ? [temp] : arg ? [arg] : []); if (ts.getESModuleInterop(compilerOptions)) { requireCall = emitHelpers().createImportStarHelper(requireCall); } @@ -107351,14 +107599,9 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)])); - // if there is a lexical 'this' in the import call arguments, ensure we indicate - // that this new function expression indicates it captures 'this' so that the - // es2015 transformer will properly substitute 'this' with '_this'. - if (containsLexicalThis) { - ts.setEmitFlags(func, 8 /* EmitFlags.CapturesThis */); - } } - return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + var downleveledImport = factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + return temp === undefined ? downleveledImport : factory.createCommaListExpression([factory.createAssignment(temp, arg), downleveledImport]); } function getHelperExpressionForExport(node, innerExpr) { if (!ts.getESModuleInterop(compilerOptions) || ts.getEmitFlags(node) & 67108864 /* EmitFlags.NeverApplyImportHelper */) { @@ -122531,10 +122774,16 @@ var ts; var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + // We can only reuse emit signatures (i.e. .d.ts signatures) if the .d.ts file is unchanged, + // which will eg be depedent on change in options like declarationDir and outDir options are unchanged. + // We need to look in oldState.compilerOptions, rather than oldCompilerOptions (i.e.we need to disregard useOldState) because + // oldCompilerOptions can be undefined if there was change in say module from None to some other option + // which would make useOldState as false since we can now use reference maps that are needed to track what to emit, what to check etc + // but that option change does not affect d.ts file name so emitSignatures should still be reused. var canCopyEmitSignatures = compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && !outFilePath && - !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); if (useOldState) { // Copy old state's changed files set (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); @@ -123749,7 +123998,7 @@ var ts; var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* CharacterCodes.slash */; if (isNonDirectorySeparatorRoot && dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths - pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart + pathPartForUserCheck.search(/[a-zA-Z]\$\//) === 0) { // Dos style nextPart nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1); if (nextDirectorySeparator === -1) { // ignore "//vda1cs4850/c$/folderAtRoot" @@ -125003,7 +125252,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_36 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -125027,9 +125276,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_12 = _loop_36(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_12 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -125098,7 +125347,7 @@ var ts; } function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - var _loop_37 = function (patternText_1) { + var _loop_36 = function (patternText_1) { var pattern = ts.normalizePath(patternText_1); var indexOfStar = pattern.indexOf("*"); // In module resolution, if `pattern` itself has an extension, a file with that extension is looked up directly, @@ -125165,9 +125414,9 @@ var ts; }; for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { var patternText_1 = _a[_i]; - var state_13 = _loop_37(patternText_1); - if (typeof state_13 === "object") - return state_13.value; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } function validateEnding(_a) { @@ -125255,15 +125504,21 @@ var ts; return undefined; } function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { + var normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPaths === undefined) { + return undefined; + } + var normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePaths = ts.flatMap(normalizedSourcePaths, function (sourcePath) { + return ts.map(normalizedTargetPaths, function (targetPath) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName)); }); + }); + var shortest = ts.min(relativePaths, ts.compareNumberOfDirectorySeparators); + if (!shortest) { return undefined; } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs - ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions) - : ts.removeFileExtension(relativePath); + ? removeExtensionAndIndexPostFix(shortest, ending, compilerOptions) + : ts.removeFileExtension(shortest); } function tryGetModuleNameAsNodeModule(_a, _b, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { var path = _a.path, isRedirect = _a.isRedirect; @@ -125400,8 +125655,8 @@ var ts; } } } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { + function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.mapDefined(rootDirs, function (rootDir) { var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath; }); @@ -127969,8 +128224,15 @@ var ts; } if (buildInfo.program) { // If there are pending changes that are not emitted, project is out of date + // When there are syntax errors, changeFileSet will have list of files changed (irrespective of noEmit) + // But in case of semantic error we need special treatment. + // Checking presence of affectedFilesPendingEmit list is fast and good way to tell if there were semantic errors and file emit was blocked + // But if noEmit is true, affectedFilesPendingEmit will have file list even if there are no semantic errors to preserve list of files to be emitted when running with noEmit false + // So with noEmit set to true, check on semantic diagnostics needs to be explicit as oppose to when it is false when only files pending emit is sufficient if (((_a = buildInfo.program.changeFileSet) === null || _a === void 0 ? void 0 : _a.length) || - (!project.options.noEmit && ((_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length))) { + (!project.options.noEmit ? + (_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length : + ts.some(buildInfo.program.semanticDiagnosticsPerFile, ts.isArray))) { return { type: ts.UpToDateStatusType.OutOfDateBuildInfo, buildInfoFile: buildInfoPath @@ -129151,6 +129413,12 @@ var ts; SemanticClassificationFormat["Original"] = "original"; SemanticClassificationFormat["TwentyTwenty"] = "2020"; })(SemanticClassificationFormat = ts.SemanticClassificationFormat || (ts.SemanticClassificationFormat = {})); + var OrganizeImportsMode; + (function (OrganizeImportsMode) { + OrganizeImportsMode["All"] = "All"; + OrganizeImportsMode["SortAndCombine"] = "SortAndCombine"; + OrganizeImportsMode["RemoveUnused"] = "RemoveUnused"; + })(OrganizeImportsMode = ts.OrganizeImportsMode || (ts.OrganizeImportsMode = {})); var CompletionTriggerKind; (function (CompletionTriggerKind) { /** Completion was triggered by typing an identifier, manual invocation (e.g Ctrl+Space) or via API. */ @@ -130196,6 +130464,8 @@ var ts; return lastTypeNode; } function getContextualTypeFromParentOrAncestorTypeNode(node, checker) { + if (node.flags & (8388608 /* NodeFlags.JSDoc */ & ~262144 /* NodeFlags.JavaScriptFile */)) + return undefined; var contextualType = getContextualTypeFromParent(node, checker); if (contextualType) return contextualType; @@ -132682,6 +132952,10 @@ var ts; return jsx === 2 /* JsxEmit.React */ || jsx === 3 /* JsxEmit.ReactNative */; } ts.jsxModeNeedsExplicitImport = jsxModeNeedsExplicitImport; + function isSourceFileFromLibrary(program, node) { + return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); + } + ts.isSourceFileFromLibrary = isSourceFileFromLibrary; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -135708,7 +135982,7 @@ var ts; if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* CompletionKind.MemberLike */ && - isClassLikeMemberCompletion(symbol, location)) { + isClassLikeMemberCompletion(symbol, location, sourceFile)) { var importAdder = void 0; (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken, formatContext), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder, replacementSpan = _b.replacementSpan); sortText = Completions.SortText.ClassMemberSnippets; // sortText has to be lower priority than the sortText for keywords. See #47852. @@ -135780,7 +136054,7 @@ var ts; data: data, }; } - function isClassLikeMemberCompletion(symbol, location) { + function isClassLikeMemberCompletion(symbol, location, sourceFile) { // TODO: support JS files. if (ts.isInJSFile(location)) { return false; @@ -135814,6 +136088,7 @@ var ts; location.parent.parent && ts.isClassElement(location.parent) && location === location.parent.name && + location.parent.getLastToken(sourceFile) === location.parent.name && ts.isClassLike(location.parent.parent)) || (location.parent && ts.isSyntaxList(location) && @@ -142975,6 +143250,12 @@ var ts; var label = ts.getTargetLabel(node.parent, node.text); return label ? [createDefinitionInfoFromName(typeChecker, label, "label" /* ScriptElementKind.label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 } + if (node.kind === 105 /* SyntaxKind.ReturnKeyword */) { + var functionDeclaration = ts.findAncestor(node.parent, function (n) { + return ts.isClassStaticBlockDeclaration(n) ? "quit" : ts.isFunctionLikeDeclaration(n); + }); + return functionDeclaration ? [createDefinitionFromSignatureDeclaration(typeChecker, functionDeclaration)] : undefined; + } if (ts.isStaticModifier(node) && ts.isClassStaticBlockDeclaration(node.parent)) { var classDecl = node.parent.parent; var _c = getSymbol(classDecl, typeChecker, stopAtAlias), symbol_1 = _c.symbol, failedAliasResolution_1 = _c.failedAliasResolution; @@ -143110,13 +143391,16 @@ var ts; if (!baseDeclaration) return; var baseTypeNode = ts.getEffectiveBaseTypeNode(baseDeclaration); - var baseType = baseTypeNode ? typeChecker.getTypeAtLocation(baseTypeNode) : undefined; - if (!baseType) + if (!baseTypeNode) + return; + var expression = ts.skipParentheses(baseTypeNode.expression); + var base = ts.isClassExpression(expression) ? expression.symbol : typeChecker.getSymbolAtLocation(expression); + if (!base) return; var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(classElement.name)); var symbol = ts.hasStaticModifier(classElement) - ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbolAtLocation(baseType.symbol, baseDeclaration), name) - : typeChecker.getPropertyOfType(baseType, name); + ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbol(base), name) + : typeChecker.getPropertyOfType(typeChecker.getDeclaredTypeOfSymbol(base), name); if (!symbol) return; return getDefinitionFromSymbol(typeChecker, symbol, node); @@ -143823,19 +144107,24 @@ var ts; return getCommentOwnerInfoWorker(commentOwner.initializer, options); case 260 /* SyntaxKind.ClassDeclaration */: case 261 /* SyntaxKind.InterfaceDeclaration */: - case 168 /* SyntaxKind.PropertySignature */: case 263 /* SyntaxKind.EnumDeclaration */: case 302 /* SyntaxKind.EnumMember */: case 262 /* SyntaxKind.TypeAliasDeclaration */: return { commentOwner: commentOwner }; + case 168 /* SyntaxKind.PropertySignature */: { + var host_1 = commentOwner; + return host_1.type && ts.isFunctionTypeNode(host_1.type) + ? { commentOwner: commentOwner, parameters: host_1.type.parameters, hasReturn: hasReturn(host_1.type, options) } + : { commentOwner: commentOwner }; + } case 240 /* SyntaxKind.VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; - var host_1 = varDeclarations.length === 1 && varDeclarations[0].initializer + var host_2 = varDeclarations.length === 1 && varDeclarations[0].initializer ? getRightHandSideOfAssignment(varDeclarations[0].initializer) : undefined; - return host_1 - ? { commentOwner: commentOwner, parameters: host_1.parameters, hasReturn: hasReturn(host_1, options) } + return host_2 + ? { commentOwner: commentOwner, parameters: host_2.parameters, hasReturn: hasReturn(host_2, options) } : { commentOwner: commentOwner }; } case 308 /* SyntaxKind.SourceFile */: @@ -143865,7 +144154,7 @@ var ts; } function hasReturn(node, options) { return !!(options === null || options === void 0 ? void 0 : options.generateReturnInDocTemplate) && - (ts.isArrowFunction(node) && ts.isExpression(node.body) + (ts.isFunctionTypeNode(node) || ts.isArrowFunction(node) && ts.isExpression(node.body) || ts.isFunctionLikeDeclaration(node) && node.body && ts.isBlock(node.body) && !!ts.forEachReturnStatement(node.body, function (n) { return n; })); } function getRightHandSideOfAssignment(rightHandSide) { @@ -144906,23 +145195,39 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program, preferences, skipDestructiveCodeActions) { + function organizeImports(sourceFile, formatContext, host, program, preferences, mode) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext, preferences: preferences }); - var coalesceAndOrganizeImports = function (importGroup) { return ts.stableSort(coalesceImports(removeUnusedImports(importGroup, sourceFile, program, skipDestructiveCodeActions)), function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }); }; + var shouldSort = mode === "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ || mode === "All" /* OrganizeImportsMode.All */; + var shouldCombine = shouldSort; // These are currently inseparable, but I draw a distinction for clarity and in case we add modes in the future. + var shouldRemove = mode === "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */ || mode === "All" /* OrganizeImportsMode.All */; + var maybeRemove = shouldRemove ? removeUnusedImports : ts.identity; + var maybeCoalesce = shouldCombine ? coalesceImports : ts.identity; + var processImportsOfSameModuleSpecifier = function (importGroup) { + var processedDeclarations = maybeCoalesce(maybeRemove(importGroup, sourceFile, program)); + return shouldSort + ? ts.stableSort(processedDeclarations, function (s1, s2) { return compareImportsOrRequireStatements(s1, s2); }) + : processedDeclarations; + }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, sourceFile.statements.filter(ts.isImportDeclaration)); - topLevelImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, coalesceAndOrganizeImports); }); - // All of the old ExportDeclarations in the file, in syntactic order. - var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); - organizeImportsWorker(topLevelExportDecls, coalesceExports); + topLevelImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier); }); + // Exports are always used + if (mode !== "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */) { + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); + } for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; if (!ambientModule.body) continue; var ambientModuleImportGroupDecls = groupImportsByNewlineContiguous(sourceFile, ambientModule.body.statements.filter(ts.isImportDeclaration)); - ambientModuleImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, coalesceAndOrganizeImports); }); - var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); - organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + ambientModuleImportGroupDecls.forEach(function (importGroupDecl) { return organizeImportsWorker(importGroupDecl, processImportsOfSameModuleSpecifier); }); + // Exports are always used + if (mode !== "RemoveUnused" /* OrganizeImportsMode.RemoveUnused */) { + var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); + } } return changeTracker.getChanges(); function organizeImportsWorker(oldImportDecls, coalesce) { @@ -144935,8 +145240,12 @@ var ts; // Consider: we could do a more careful check that this trivia is actually a header, // but the consequences of being wrong are very minor. ts.suppressLeadingTrivia(oldImportDecls[0]); - var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); - var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); + var oldImportGroups = shouldCombine + ? ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }) + : [oldImportDecls]; + var sortedImportGroups = shouldSort + ? ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }) + : oldImportGroups; var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) ? coalesce(importGroup) @@ -145000,11 +145309,7 @@ var ts; } return false; } - function removeUnusedImports(oldImports, sourceFile, program, skipDestructiveCodeActions) { - // As a precaution, consider unused import detection to be destructive (GH #43051) - if (skipDestructiveCodeActions) { - return oldImports; - } + function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); @@ -145860,7 +146165,7 @@ var ts; return bestMatch; } function betterMatch(a, b) { - return ts.min(a, b, compareMatches); + return ts.min([a, b], compareMatches); } function compareMatches(a, b) { return a === undefined ? 1 /* Comparison.GreaterThan */ : b === undefined ? -1 /* Comparison.LessThan */ @@ -146469,8 +146774,8 @@ var ts; } if (ts.scanner.getToken() === 15 /* SyntaxKind.TemplateHead */) { var stack = [ts.scanner.getToken()]; - var token = ts.scanner.scan(); loop: while (ts.length(stack)) { + var token = ts.scanner.scan(); switch (token) { case 1 /* SyntaxKind.EndOfFileToken */: break loop; @@ -146498,7 +146803,6 @@ var ts; } break; } - token = ts.scanner.scan(); } nextToken(); } @@ -148977,7 +149281,7 @@ var ts; tags = signature.getJsDocTags(); if (allSignatures.length > 1 && documentation.length === 0 && tags.length === 0) { documentation = allSignatures[0].getDocumentationComment(typeChecker); - tags = allSignatures[0].getJsDocTags(); + tags = allSignatures[0].getJsDocTags().filter(function (tag) { return tag.name !== "deprecated"; }); // should only include @deprecated JSDoc tag on the first overload (#49368) } } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { @@ -149320,7 +149624,7 @@ var ts; return false; } function shouldRescanJsxText(node) { - return ts.isJsxText(node); + return ts.isJsxText(node) || ts.isJsxElement(node) && (lastTokenInfo === null || lastTokenInfo === void 0 ? void 0 : lastTokenInfo.token.kind) === 11 /* SyntaxKind.JsxText */; } function shouldRescanSlashToken(container) { return container.kind === 13 /* SyntaxKind.RegularExpressionLiteral */; @@ -150089,10 +150393,10 @@ var ts; !nodeIsInDecoratorContext(context.nextTokenParent); } function nodeIsInDecoratorContext(node) { - while (ts.isExpressionNode(node)) { + while (node && ts.isExpression(node)) { node = node.parent; } - return node.kind === 167 /* SyntaxKind.Decorator */; + return node && node.kind === 167 /* SyntaxKind.Decorator */; } function isStartOfVariableDeclarationList(context) { return context.currentTokenParent.kind === 258 /* SyntaxKind.VariableDeclarationList */ && @@ -153010,6 +153314,26 @@ var ts; function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } + function endPositionToDeleteNodeInList(sourceFile, node, prevNode, nextNode) { + var end = startPositionToDeleteNodeInList(sourceFile, nextNode); + if (prevNode === undefined || ts.positionsAreOnSameLine(getAdjustedEndPosition(sourceFile, node, {}), end, sourceFile)) { + return end; + } + var token = ts.findPrecedingToken(nextNode.getStart(sourceFile), sourceFile); + if (isSeparator(node, token)) { + var prevToken = ts.findPrecedingToken(node.getStart(sourceFile), sourceFile); + if (isSeparator(prevNode, prevToken)) { + var pos = ts.skipTrivia(sourceFile.text, token.getEnd(), /*stopAfterLineBreak*/ true, /*stopAtComments*/ true); + if (ts.positionsAreOnSameLine(prevToken.getStart(sourceFile), token.getStart(sourceFile), sourceFile)) { + return ts.isLineBreak(sourceFile.text.charCodeAt(pos - 1)) ? pos - 1 : pos; + } + if (ts.isLineBreak(sourceFile.text.charCodeAt(pos))) { + return pos; + } + } + } + return end; + } function getClassOrObjectBraceEnds(cls, sourceFile) { var open = ts.findChildOfKind(cls, 18 /* SyntaxKind.OpenBraceToken */, sourceFile); var close = ts.findChildOfKind(cls, 19 /* SyntaxKind.CloseBraceToken */, sourceFile); @@ -153567,7 +153891,7 @@ var ts; deletedNodesInLists.add(node); changes.deleteRange(sourceFile, { pos: startPositionToDeleteNodeInList(sourceFile, node), - end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : endPositionToDeleteNodeInList(sourceFile, node, containingList[index - 1], containingList[index + 1]), }); } })(textChanges = ts.textChanges || (ts.textChanges = {})); @@ -154037,6 +154361,15 @@ var ts; }); } function makeChange(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { + if (ts.isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) { + var exprType = checker.getTypeAtLocation(insertionSite); + var asyncIter = checker.getAsyncIterableType(); + if (asyncIter && checker.isTypeAssignableTo(exprType, asyncIter)) { + var forOf = insertionSite.parent; + changeTracker.replaceNode(sourceFile, forOf, ts.factory.updateForOfStatement(forOf, ts.factory.createToken(133 /* SyntaxKind.AwaitKeyword */), forOf.initializer, forOf.expression, forOf.statement)); + return; + } + } if (ts.isBinaryExpression(insertionSite)) { for (var _i = 0, _a = [insertionSite.left, insertionSite.right]; _i < _a.length; _i++) { var side = _a[_i]; @@ -157762,6 +158095,143 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixImportNonExportedMember"; + var errorCodes = [ + ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixId], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span, program = context.program; + var info = getInfo(sourceFile, span.start, program); + if (info === undefined) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, program, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId, ts.Diagnostics.Export_all_referenced_locals)]; + }, + getAllCodeActions: function (context) { + var program = context.program; + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + var exports = new ts.Map(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, program); + if (info === undefined) + return undefined; + var exportName = info.exportName, node = info.node, moduleSourceFile = info.moduleSourceFile; + if (tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly) === undefined && ts.canHaveExportModifier(node)) { + changes.insertExportModifier(moduleSourceFile, node); + } + else { + var moduleExports = exports.get(moduleSourceFile) || { typeOnlyExports: [], exports: [] }; + if (exportName.isTypeOnly) { + moduleExports.typeOnlyExports.push(exportName); + } + else { + moduleExports.exports.push(exportName); + } + exports.set(moduleSourceFile, moduleExports); + } + }); + exports.forEach(function (moduleExports, moduleSourceFile) { + var exportDeclaration = tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ true); + if (exportDeclaration && exportDeclaration.isTypeOnly) { + doChanges(changes, program, moduleSourceFile, moduleExports.typeOnlyExports, exportDeclaration); + doChanges(changes, program, moduleSourceFile, moduleExports.exports, tryGetExportDeclaration(moduleSourceFile, /*isTypeOnly*/ false)); + } + else { + doChanges(changes, program, moduleSourceFile, __spreadArray(__spreadArray([], moduleExports.exports, true), moduleExports.typeOnlyExports, true), exportDeclaration); + } + }); + })); + } + }); + function getInfo(sourceFile, pos, program) { + var _a; + var token = ts.getTokenAtPosition(sourceFile, pos); + if (ts.isIdentifier(token)) { + var importDeclaration = ts.findAncestor(token, ts.isImportDeclaration); + if (importDeclaration === undefined) + return undefined; + var moduleSpecifier = ts.isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier.text : undefined; + if (moduleSpecifier === undefined) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, moduleSpecifier, /*mode*/ undefined); + if (resolvedModule === undefined) + return undefined; + var moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName); + if (moduleSourceFile === undefined || ts.isSourceFileFromLibrary(program, moduleSourceFile)) + return undefined; + var moduleSymbol = moduleSourceFile.symbol; + var locals = (_a = moduleSymbol.valueDeclaration) === null || _a === void 0 ? void 0 : _a.locals; + if (locals === undefined) + return undefined; + var localSymbol = locals.get(token.escapedText); + if (localSymbol === undefined) + return undefined; + var node = getNodeOfSymbol(localSymbol); + if (node === undefined) + return undefined; + var exportName = { node: token, isTypeOnly: ts.isTypeDeclaration(node) }; + return { exportName: exportName, node: node, moduleSourceFile: moduleSourceFile, moduleSpecifier: moduleSpecifier }; + } + return undefined; + } + function doChange(changes, program, _a) { + var exportName = _a.exportName, node = _a.node, moduleSourceFile = _a.moduleSourceFile; + var exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); + if (exportDeclaration) { + updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]); + } + else if (ts.canHaveExportModifier(node)) { + changes.insertExportModifier(moduleSourceFile, node); + } + else { + createExport(changes, program, moduleSourceFile, [exportName]); + } + } + function doChanges(changes, program, sourceFile, moduleExports, node) { + if (ts.length(moduleExports)) { + if (node) { + updateExport(changes, program, sourceFile, node, moduleExports); + } + else { + createExport(changes, program, sourceFile, moduleExports); + } + } + } + function tryGetExportDeclaration(sourceFile, isTypeOnly) { + var predicate = function (node) { + return ts.isExportDeclaration(node) && (isTypeOnly && node.isTypeOnly || !node.isTypeOnly); + }; + return ts.findLast(sourceFile.statements, predicate); + } + function updateExport(changes, program, sourceFile, node, names) { + var namedExports = node.exportClause && ts.isNamedExports(node.exportClause) ? node.exportClause.elements : ts.factory.createNodeArray([]); + var allowTypeModifier = !node.isTypeOnly && !!(program.getCompilerOptions().isolatedModules || ts.find(namedExports, function (e) { return e.isTypeOnly; })); + changes.replaceNode(sourceFile, node, ts.factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, ts.factory.createNamedExports(ts.factory.createNodeArray(__spreadArray(__spreadArray([], namedExports, true), createExportSpecifiers(names, allowTypeModifier), true), /*hasTrailingComma*/ namedExports.hasTrailingComma)), node.moduleSpecifier, node.assertClause)); + } + function createExport(changes, program, sourceFile, names) { + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, ts.factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, ts.factory.createNamedExports(createExportSpecifiers(names, /*allowTypeModifier*/ !!program.getCompilerOptions().isolatedModules)), /*moduleSpecifier*/ undefined, /*assertClause*/ undefined)); + } + function createExportSpecifiers(names, allowTypeModifier) { + return ts.factory.createNodeArray(ts.map(names, function (n) { return ts.factory.createExportSpecifier(allowTypeModifier && n.isTypeOnly, /*propertyName*/ undefined, n.node); })); + } + function getNodeOfSymbol(symbol) { + if (symbol.valueDeclaration === undefined) { + return ts.firstOrUndefined(symbol.declarations); + } + var declaration = symbol.valueDeclaration; + var variableStatement = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : undefined; + return variableStatement && ts.length(variableStatement.declarationList.declarations) === 1 ? variableStatement : declaration; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -158292,7 +158762,7 @@ var ts; var argIndex = ts.findIndex(parent.parent.arguments, function (arg) { return arg === parent; }); if (argIndex < 0) return undefined; - var signature = ts.singleOrUndefined(checker.getSignaturesOfType(checker.getTypeAtLocation(parent.parent.expression), 0 /* SignatureKind.Call */)); + var signature = checker.getResolvedSignature(parent.parent); if (!(signature && signature.declaration && signature.parameters[argIndex])) return undefined; var param = signature.parameters[argIndex].valueDeclaration; @@ -158339,13 +158809,13 @@ var ts; if (ts.isIdentifier(token) && ts.isCallExpression(parent.parent)) { var moduleDeclaration = ts.find(symbol.declarations, ts.isModuleDeclaration); var moduleDeclarationSourceFile = moduleDeclaration === null || moduleDeclaration === void 0 ? void 0 : moduleDeclaration.getSourceFile(); - if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { + if (moduleDeclaration && moduleDeclarationSourceFile && !ts.isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { return { kind: InfoKind.Function, token: token, call: parent.parent, sourceFile: sourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleDeclaration }; } var moduleSourceFile = ts.find(symbol.declarations, ts.isSourceFile); if (sourceFile.commonJsModuleIndicator) return undefined; - if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) { + if (moduleSourceFile && !ts.isSourceFileFromLibrary(program, moduleSourceFile)) { return { kind: InfoKind.Function, token: token, call: parent.parent, sourceFile: moduleSourceFile, modifierFlags: 1 /* ModifierFlags.Export */, parentDeclaration: moduleSourceFile }; } } @@ -158355,7 +158825,7 @@ var ts; return undefined; // Prefer to change the class instead of the interface if they are merged var declaration = classDeclaration || ts.find(symbol.declarations, function (d) { return ts.isInterfaceDeclaration(d) || ts.isTypeLiteralNode(d); }); - if (declaration && !isSourceFileFromLibrary(program, declaration.getSourceFile())) { + if (declaration && !ts.isSourceFileFromLibrary(program, declaration.getSourceFile())) { var makeStatic = !ts.isTypeLiteralNode(declaration) && (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); if (makeStatic && (ts.isPrivateIdentifier(token) || ts.isInterfaceDeclaration(declaration))) return undefined; @@ -158367,14 +158837,11 @@ var ts; return { kind: InfoKind.TypeLikeDeclaration, token: token, call: call, modifierFlags: modifierFlags, parentDeclaration: declaration, declSourceFile: declSourceFile, isJSFile: isJSFile }; } var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); - if (enumDeclaration && !(leftExpressionType.flags & 1056 /* TypeFlags.EnumLike */) && !ts.isPrivateIdentifier(token) && !isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { + if (enumDeclaration && !(leftExpressionType.flags & 1056 /* TypeFlags.EnumLike */) && !ts.isPrivateIdentifier(token) && !ts.isSourceFileFromLibrary(program, enumDeclaration.getSourceFile())) { return { kind: InfoKind.Enum, token: token, parentDeclaration: enumDeclaration }; } return undefined; } - function isSourceFileFromLibrary(program, node) { - return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); - } function getActionsForMissingMemberDeclaration(context, info) { return info.isJSFile ? ts.singleElementArray(createActionForAddMissingMemberInJavascriptFile(context, info)) : createActionsForAddMissingMemberInTypeScriptFile(context, info); @@ -163800,8 +164267,8 @@ var ts; var i = 0; for (var _i = 0, extractions_1 = extractions; _i < extractions_1.length; _i++) { var _a = extractions_1[_i], functionExtraction = _a.functionExtraction, constantExtraction = _a.constantExtraction; - var description = functionExtraction.description; if (refactor.refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + var description = functionExtraction.description; if (functionExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will @@ -163825,15 +164292,15 @@ var ts; } } if (refactor.refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + var description = constantExtraction.description; if (constantExtraction.errors.length === 0) { // Don't issue refactorings with duplicated names. // Scopes come back in "innermost first" order, so extractions will // preferentially go into nearer scopes - var description_1 = constantExtraction.description; - if (!usedConstantNames.has(description_1)) { - usedConstantNames.set(description_1, true); + if (!usedConstantNames.has(description)) { + usedConstantNames.set(description, true); constantActions.push({ - description: description_1, + description: description, name: "constant_scope_".concat(i), kind: extractConstantAction.kind }); @@ -163978,7 +164445,6 @@ var ts; var start = cursorRequest ? getExtractableParent(startToken) : ts.getParentNodeInSpan(startToken, sourceFile, adjustedSpan); // Do the same for the ending position var end = cursorRequest ? start : ts.getParentNodeInSpan(endToken, sourceFile, adjustedSpan); - var declarations = []; // We'll modify these flags as we walk the tree to collect data // about what things need to be done as part of the extraction. var rangeFacts = RangeFacts.None; @@ -164021,7 +164487,7 @@ var ts; // the expression. return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } - return { targetRange: { range: statements, facts: rangeFacts, declarations: declarations, thisNode: thisNode } }; + return { targetRange: { range: statements, facts: rangeFacts, thisNode: thisNode } }; } if (ts.isReturnStatement(start) && !start.expression) { // Makes no sense to extract an expression-less return statement. @@ -164033,7 +164499,7 @@ var ts; if (errors) { return { errors: errors }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations, thisNode: thisNode } }; // TODO: GH#18217 + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode: thisNode } }; // TODO: GH#18217 /** * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. * @param node The unrefined extraction node. @@ -164045,10 +164511,10 @@ var ts; } } else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { - var declarations_6 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; + var declarations = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, declarations_5 = declarations_6; _i < declarations_5.length; _i++) { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { var declaration = declarations_5[_i]; if (declaration.initializer) { numInitializers++; @@ -164148,7 +164614,6 @@ var ts; (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } - declarations.push(node.symbol); } // Some things can't be extracted in certain situations switch (node.kind) { @@ -165873,7 +166338,7 @@ var ts; function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { var checker = program.getTypeChecker(); var prologueDirectives = ts.takeWhile(oldFile.statements, ts.isPrologueDirective); - if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + if (oldFile.externalModuleIndicator === undefined && oldFile.commonJsModuleIndicator === undefined && usage.oldImportsNeededByNewFile.size() === 0) { deleteMovedStatements(oldFile, toMove.ranges, changes); return __spreadArray(__spreadArray([], prologueDirectives, true), toMove.all, true); } @@ -166114,7 +166579,12 @@ var ts; switch (name.kind) { case 79 /* SyntaxKind.Identifier */: if (isUnused(name)) { - changes.delete(sourceFile, name); + if (varDecl.initializer && ts.isRequireCall(varDecl.initializer, /*requireStringLiteralLikeArgument*/ true)) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && ts.length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); + } + else { + changes.delete(sourceFile, name); + } } break; case 204 /* SyntaxKind.ArrayBindingPattern */: @@ -166346,6 +166816,9 @@ var ts; ts.copyEntries(this.map, clone.map); return clone; }; + SymbolSet.prototype.size = function () { + return this.map.size; + }; return SymbolSet; }()); function isTopLevelDeclaration(node) { @@ -166434,7 +166907,8 @@ var ts; if (useEs6Exports) { return !ts.isExpressionStatement(decl) && ts.hasSyntacticModifier(decl, 1 /* ModifierFlags.Export */) || !!(name && ((_a = sourceFile.symbol.exports) === null || _a === void 0 ? void 0 : _a.has(name.escapedText))); } - return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + return !!sourceFile.symbol && !!sourceFile.symbol.exports && + getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); } function addExport(decl, useEs6Exports) { return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); @@ -168194,8 +168668,8 @@ var ts; tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); } }; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; _loop_20(declaration); } } @@ -168221,8 +168695,8 @@ var ts; if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); }; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; _loop_21(declaration); } } @@ -169392,12 +169866,14 @@ var ts; return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } function organizeImports(args, formatOptions, preferences) { + var _a; if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(args.type === "file"); var sourceFile = getValidSourceFile(args.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions, host); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, args.skipDestructiveCodeActions); + var mode = (_a = args.mode) !== null && _a !== void 0 ? _a : (args.skipDestructiveCodeActions ? "SortAndCombine" /* OrganizeImportsMode.SortAndCombine */ : "All" /* OrganizeImportsMode.All */); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences, mode); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 284a066b2c904..764e544746138 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -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 = "".concat(ts.versionMajorMinor, ".1-beta"); + ts.version = "".concat(ts.versionMajorMinor, ".2-rc"); /* @internal */ var Comparison; (function (Comparison) { @@ -1881,8 +1881,8 @@ var ts; return compareValues(a === null || a === void 0 ? void 0 : a.start, b === null || b === void 0 ? void 0 : b.start) || compareValues(a === null || a === void 0 ? void 0 : a.length, b === null || b === void 0 ? void 0 : b.length); } ts.compareTextSpans = compareTextSpans; - function min(a, b, compare) { - return compare(a, b) === -1 /* Comparison.LessThan */ ? a : b; + function min(items, compare) { + return reduceLeft(items, function (x, y) { return compare(x, y) === -1 /* Comparison.LessThan */ ? x : y; }); } ts.min = min; /** @@ -3195,11 +3195,13 @@ var ts; // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers // > MUST NOT include leading zeroes. var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; // https://semver.org/#spec-item-10 // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated // > identifiers immediately following the patch or pre-release version. Identifiers MUST // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + var buildPartRegExp = /^[a-z0-9-]+$/i; // https://semver.org/#spec-item-9 // > Numeric identifiers MUST NOT include leading zeroes. var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; @@ -3219,13 +3221,15 @@ var ts; ts.Debug.assert(major >= 0, "Invalid argument: major"); ts.Debug.assert(minor >= 0, "Invalid argument: minor"); ts.Debug.assert(patch >= 0, "Invalid argument: patch"); - ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); - ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + var prereleaseArray = prerelease ? ts.isArray(prerelease) ? prerelease : prerelease.split(".") : ts.emptyArray; + var buildArray = build ? ts.isArray(build) ? build : build.split(".") : ts.emptyArray; + ts.Debug.assert(ts.every(prereleaseArray, function (s) { return prereleasePartRegExp.test(s); }), "Invalid argument: prerelease"); + ts.Debug.assert(ts.every(buildArray, function (s) { return buildPartRegExp.test(s); }), "Invalid argument: build"); this.major = major; this.minor = minor; this.patch = patch; - this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray; - this.build = build ? build.split(".") : ts.emptyArray; + this.prerelease = prereleaseArray; + this.build = buildArray; } Version.tryParse = function (text) { var result = tryParseComponents(text); @@ -3264,6 +3268,10 @@ var ts; default: return ts.Debug.assertNever(field); } }; + Version.prototype.with = function (fields) { + var _a = fields.major, major = _a === void 0 ? this.major : _a, _b = fields.minor, minor = _b === void 0 ? this.minor : _b, _c = fields.patch, patch = _c === void 0 ? this.patch : _c, _d = fields.prerelease, prerelease = _d === void 0 ? this.prerelease : _d, _e = fields.build, build = _e === void 0 ? this.build : _e; + return new Version(major, minor, patch, prerelease, build); + }; Version.prototype.toString = function () { var result = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); if (ts.some(this.prerelease)) @@ -3272,7 +3280,7 @@ var ts; result += "+".concat(this.build.join(".")); return result; }; - Version.zero = new Version(0, 0, 0); + Version.zero = new Version(0, 0, 0, ["0"]); return Version; }()); ts.Version = Version; @@ -3355,6 +3363,10 @@ var ts; } return undefined; }; + /** + * Tests whether a version matches the range. This is equivalent to `satisfies(version, range, { includePrerelease: true })`. + * in `node-semver`. + */ VersionRange.prototype.test = function (version) { if (typeof version === "string") version = new Version(version); @@ -3465,19 +3477,20 @@ var ts; break; case "<": case ">=": - comparators.push(createComparator(operator, version)); + comparators.push(isWildcard(minor) || isWildcard(patch) ? createComparator(operator, version.with({ prerelease: "0" })) : + createComparator(operator, version)); break; case "<=": case ">": - comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : - isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major").with({ prerelease: "0" })) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor").with({ prerelease: "0" })) : createComparator(operator, version)); break; case "=": case undefined: if (isWildcard(minor) || isWildcard(patch)) { - comparators.push(createComparator(">=", version)); - comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + comparators.push(createComparator(">=", version.with({ prerelease: "0" }))); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor").with({ prerelease: "0" }))); } else { comparators.push(createComparator("=", version)); @@ -5086,8 +5099,8 @@ var ts; NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance"; NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic"; NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper"; - NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAccessInAsync"] = 2048] = "MethodWithSuperPropertyAccessInAsync"; + NodeCheckFlags[NodeCheckFlags["MethodWithSuperPropertyAssignmentInAsync"] = 4096] = "MethodWithSuperPropertyAssignmentInAsync"; NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments"; NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed"; NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass"; @@ -6722,7 +6735,7 @@ var ts; } /*@internal*/ function createSystemWatchFunctions(_a) { - var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, defaultWatchFileKind = _a.defaultWatchFileKind, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; + var pollingWatchFileWorker = _a.pollingWatchFileWorker, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatchWorker = _a.fsWatchWorker, fileSystemEntryExists = _a.fileSystemEntryExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, getCurrentDirectory = _a.getCurrentDirectory, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory, inodeWatching = _a.inodeWatching, sysLog = _a.sysLog; var pollingWatches = new ts.Map(); var fsWatches = new ts.Map(); var fsWatchesRecursive = new ts.Map(); @@ -6788,8 +6801,8 @@ var ts; return useNonPollingWatchers ? // Use notifications from FS to watch with falling back to fs.watchFile generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) : - // Default to do not use fixed polling interval - { watchFile: (defaultWatchFileKind === null || defaultWatchFileKind === void 0 ? void 0 : defaultWatchFileKind()) || ts.WatchFileKind.UseFsEvents }; + // Default to using fs events + { watchFile: ts.WatchFileKind.UseFsEvents }; } } function generateWatchFileOptions(watchFile, fallbackPolling, options) { @@ -7061,7 +7074,6 @@ var ts; tscWatchFile: process.env.TSC_WATCHFILE, useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER, tscWatchDirectory: process.env.TSC_WATCHDIRECTORY, - defaultWatchFileKind: function () { var _a, _b; return (_b = (_a = sys).defaultWatchFileKind) === null || _b === void 0 ? void 0 : _b.call(_a); }, inodeWatching: isLinuxOrMacOs, sysLog: sysLog, }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory; @@ -9572,6 +9584,10 @@ var ts; Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted: diag(6399, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitte_6399", "Project '{0}' is out of date because buildinfo file '{1}' indicates that some of the changes were not emitted"), Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files: diag(6400, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_fil_6400", "Project '{0}' is up to date but needs to update timestamps of output files that are older than input files"), Project_0_is_out_of_date_because_there_was_error_reading_file_1: diag(6401, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_there_was_error_reading_file_1_6401", "Project '{0}' is out of date because there was error reading file '{1}'"), + Resolving_in_0_mode_with_conditions_1: diag(6402, ts.DiagnosticCategory.Message, "Resolving_in_0_mode_with_conditions_1_6402", "Resolving in {0} mode with conditions {1}."), + Matched_0_condition_1: diag(6403, ts.DiagnosticCategory.Message, "Matched_0_condition_1_6403", "Matched '{0}' condition '{1}'."), + Using_0_subpath_1_with_target_2: diag(6404, ts.DiagnosticCategory.Message, "Using_0_subpath_1_with_target_2_6404", "Using '{0}' subpath '{1}' with target '{2}'."), + Saw_non_matching_condition_0: diag(6405, ts.DiagnosticCategory.Message, "Saw_non_matching_condition_0_6405", "Saw non-matching condition '{0}'."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -9888,6 +9904,8 @@ var ts; Remove_type_from_import_of_0_from_1: diag(90056, ts.DiagnosticCategory.Message, "Remove_type_from_import_of_0_from_1_90056", "Remove 'type' from import of '{0}' from \"{1}\""), Add_import_from_0: diag(90057, ts.DiagnosticCategory.Message, "Add_import_from_0_90057", "Add import from \"{0}\""), Update_import_from_0: diag(90058, ts.DiagnosticCategory.Message, "Update_import_from_0_90058", "Update import from \"{0}\""), + Export_0_from_module_1: diag(90059, ts.DiagnosticCategory.Message, "Export_0_from_module_1_90059", "Export '{0}' from module '{1}'"), + Export_all_referenced_locals: diag(90060, ts.DiagnosticCategory.Message, "Export_all_referenced_locals_90060", "Export all referenced locals"), 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}"), @@ -11345,7 +11363,7 @@ var ts; return -1; } function peekExtendedUnicodeEscape() { - if (languageVersion >= 2 /* ScriptTarget.ES2015 */ && codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { + if (codePointAt(text, pos + 1) === 117 /* CharacterCodes.u */ && codePointAt(text, pos + 2) === 123 /* CharacterCodes.openBrace */) { var start_2 = pos; pos += 3; var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); @@ -21648,6 +21666,32 @@ var ts; return parameter.kind === 343 /* SyntaxKind.JSDocParameterTag */ ? (_a = parameter.typeExpression) === null || _a === void 0 ? void 0 : _a.type : parameter.type; } ts.getParameterTypeNode = getParameterTypeNode; + function isTypeDeclaration(node) { + switch (node.kind) { + case 165 /* SyntaxKind.TypeParameter */: + case 260 /* SyntaxKind.ClassDeclaration */: + case 261 /* SyntaxKind.InterfaceDeclaration */: + case 262 /* SyntaxKind.TypeAliasDeclaration */: + case 263 /* SyntaxKind.EnumDeclaration */: + case 348 /* SyntaxKind.JSDocTypedefTag */: + case 341 /* SyntaxKind.JSDocCallbackTag */: + case 342 /* SyntaxKind.JSDocEnumTag */: + return true; + case 270 /* SyntaxKind.ImportClause */: + return node.isTypeOnly; + case 273 /* SyntaxKind.ImportSpecifier */: + case 278 /* SyntaxKind.ExportSpecifier */: + return node.parent.parent.isTypeOnly; + default: + return false; + } + } + ts.isTypeDeclaration = isTypeDeclaration; + function canHaveExportModifier(node) { + return ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) || isTypeDeclaration(node) || (ts.isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node)); + } + ts.canHaveExportModifier = canHaveExportModifier; })(ts || (ts = {})); /* @internal */ var ts; @@ -21656,13 +21700,11 @@ var ts; * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator. */ function createBaseNodeFactory() { - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name return { createBaseSourceFileNode: createBaseSourceFileNode, createBaseIdentifierNode: createBaseIdentifierNode, @@ -23126,7 +23168,7 @@ var ts; return node; } // @api - function createIdentifier(text, typeArguments, originalKeywordKind) { + function createIdentifier(text, typeArguments, originalKeywordKind, hasExtendedUnicodeEscape) { var node = createBaseIdentifier(text, originalKeywordKind); if (typeArguments) { // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations @@ -23135,6 +23177,10 @@ var ts; if (node.originalKeywordKind === 133 /* SyntaxKind.AwaitKeyword */) { node.transformFlags |= 67108864 /* TransformFlags.ContainsPossibleTopLevelAwait */; } + if (hasExtendedUnicodeEscape) { + node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; + node.transformFlags |= 1024 /* TransformFlags.ContainsES2015 */; + } return node; } // @api @@ -27590,11 +27636,9 @@ var ts; rawTextScanner.setText("`" + rawText + "`"); break; case 15 /* SyntaxKind.TemplateHead */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("`" + rawText + "${"); break; case 16 /* SyntaxKind.TemplateMiddle */: - // tslint:disable-next-line no-invalid-template-strings rawTextScanner.setText("}" + rawText + "${"); break; case 17 /* SyntaxKind.TemplateTail */: @@ -27953,7 +27997,6 @@ var ts; return node; } ts.createInputFiles = createInputFiles; - // tslint:disable-next-line variable-name var SourceMapSource; /** * Create an external source map source file reference @@ -28745,6 +28788,8 @@ var ts; // - The verb (`next`, `throw`, or `return` method) to delegate to the expression // of a `yield*`. // - The result of evaluating the verb delegated to the expression of a `yield*`. + // g A temporary variable that holds onto the generator object until the generator + // is started, allowing it to also act as the `suspendedStart` state. // // functions: // verb(n) Creates a bound callback to the `step` function for opcode `n`. @@ -28783,7 +28828,7 @@ var ts; importName: "__generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; // ES Module Helpers ts.createBindingHelper = { @@ -32087,13 +32132,11 @@ var ts; var scanner = ts.createScanner(99 /* ScriptTarget.Latest */, /*skipTrivia*/ true); var disallowInAndDecoratorContext = 4096 /* NodeFlags.DisallowInContext */ | 16384 /* NodeFlags.DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks - // tslint:disable variable-name var NodeConstructor; var TokenConstructor; var IdentifierConstructor; var PrivateIdentifierConstructor; var SourceFileConstructor; - // tslint:enable variable-name function countNode(node) { nodeCount++; return node; @@ -33069,8 +33112,9 @@ var ts; // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker var originalKeywordKind = token(); var text = internIdentifier(scanner.getTokenValue()); + var hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape(); nextTokenWithoutCheck(); - return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos); + return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind, hasExtendedUnicodeEscape), pos); } if (token() === 80 /* SyntaxKind.PrivateIdentifier */) { parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); @@ -42209,12 +42253,23 @@ var ts; } function writeConfigurations() { // Filter applicable options to place in the file - var categorizedOptions = ts.createMultiMap(); + var categorizedOptions = new ts.Map(); + // Set allowed categories in order + categorizedOptions.set(ts.Diagnostics.Projects, []); + categorizedOptions.set(ts.Diagnostics.Language_and_Environment, []); + categorizedOptions.set(ts.Diagnostics.Modules, []); + categorizedOptions.set(ts.Diagnostics.JavaScript_Support, []); + categorizedOptions.set(ts.Diagnostics.Emit, []); + categorizedOptions.set(ts.Diagnostics.Interop_Constraints, []); + categorizedOptions.set(ts.Diagnostics.Type_Checking, []); + categorizedOptions.set(ts.Diagnostics.Completeness, []); for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { var option = optionDeclarations_1[_i]; - var category = option.category; if (isAllowedOptionForOutput(option)) { - categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + var listForCategory = categorizedOptions.get(option.category); + if (!listForCategory) + categorizedOptions.set(option.category, listForCategory = []); + listForCategory.push(option); } } // Serialize all options and their descriptions @@ -42225,7 +42280,7 @@ var ts; if (entries.length !== 0) { entries.push({ value: "" }); } - entries.push({ value: "/* ".concat(category, " */") }); + entries.push({ value: "/* ".concat(ts.getLocaleSpecificMessage(category), " */") }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -44267,6 +44322,9 @@ var ts; requestContainingDirectory: containingDirectory, reportDiagnostic: function (diag) { return void diagnostics.push(diag); }, }; + if (traceEnabled && ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && ts.getEmitModuleResolutionKind(compilerOptions) <= ts.ModuleResolutionKind.NodeNext) { + trace(host, ts.Diagnostics.Resolving_in_0_mode_with_conditions_1, features & NodeResolutionFeatures.EsmMode ? "ESM" : "CJS", conditions.map(function (c) { return "'".concat(c, "'"); }).join(", ")); + } var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state.resultFromCache); function tryResolve(extensions) { @@ -44856,7 +44914,7 @@ var ts; } if (mainExport) { var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false); - return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false, "."); } } else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) { @@ -44936,7 +44994,7 @@ var ts; var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!ts.endsWith(moduleName, ts.directorySeparator) && moduleName.indexOf("*") === -1 && ts.hasProperty(lookupTable, moduleName)) { var target = lookupTable[moduleName]; - return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName); } var expandingKeys = ts.sort(ts.filter(ts.getOwnKeys(lookupTable), function (k) { return k.indexOf("*") !== -1 || ts.endsWith(k, "/"); }), comparePatternKeys); for (var _i = 0, expandingKeys_1 = expandingKeys; _i < expandingKeys_1.length; _i++) { @@ -44945,17 +45003,17 @@ var ts; var target = lookupTable[potentialTarget]; var starPos = potentialTarget.indexOf("*"); var subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.endsWith(potentialTarget, "*") && ts.startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length - 1); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ true, potentialTarget); } else if (ts.startsWith(moduleName, potentialTarget)) { var target = lookupTable[potentialTarget]; var subpath = moduleName.substring(potentialTarget.length); - return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false); + return loadModuleFromTargetImportOrExport(target, subpath, /*pattern*/ false, potentialTarget); } } function matchesPatternWithTrailer(target, name) { @@ -44972,7 +45030,7 @@ var ts; */ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) { return loadModuleFromTargetImportOrExport; - function loadModuleFromTargetImportOrExport(target, subpath, pattern) { + function loadModuleFromTargetImportOrExport(target, subpath, pattern, key) { if (typeof target === "string") { if (!pattern && subpath.length > 0 && !ts.endsWith(target, "/")) { if (state.traceEnabled) { @@ -44983,6 +45041,8 @@ var ts; if (!ts.startsWith(target, "./")) { if (isImports && !ts.startsWith(target, "../") && !ts.startsWith(target, "/") && !ts.isRootedDiskPath(target)) { var combinedLookup = pattern ? target.replace(/\*/g, subpath) : target + subpath; + traceIfEnabled(state, ts.Diagnostics.Using_0_subpath_1_with_target_2, "imports", key, combinedLookup); + traceIfEnabled(state, ts.Diagnostics.Resolving_module_0_from_1, combinedLookup, scope.packageDirectory + "/"); var result = nodeModuleNameResolverWorker(state.features, combinedLookup, scope.packageDirectory + "/", state.compilerOptions, state.host, cache, [extensions], redirectedReference); return toSearchResult(result.resolvedModule ? { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId, originalPath: result.resolvedModule.originalPath } : undefined); } @@ -45009,6 +45069,9 @@ var ts; } return toSearchResult(/*value*/ undefined); } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Using_0_subpath_1_with_target_2, isImports ? "imports" : "exports", key, pattern ? target.replace(/\*/g, subpath) : target + subpath); + } var finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); var inputLink = tryLoadInputFileForPath(finalPath, subpath, ts.combinePaths(scope.packageDirectory, "package.json"), isImports); if (inputLink) @@ -45018,14 +45081,18 @@ var ts; else if (typeof target === "object" && target !== null) { // eslint-disable-line no-null/no-null if (!Array.isArray(target)) { for (var _i = 0, _a = ts.getOwnKeys(target); _i < _a.length; _i++) { - var key = _a[_i]; - if (key === "default" || state.conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(state.conditions, key)) { - var subTarget = target[key]; - var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern); + var condition = _a[_i]; + if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) { + traceIfEnabled(state, ts.Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition); + var subTarget = target[condition]; + var result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key); if (result) { return result; } } + else { + traceIfEnabled(state, ts.Diagnostics.Saw_non_matching_condition_0, condition); + } } return undefined; } @@ -45038,7 +45105,7 @@ var ts; } for (var _b = 0, target_2 = target; _b < target_2.length; _b++) { var elem = target_2[_b]; - var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern); + var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern, key); if (result) { return result; } @@ -45454,6 +45521,15 @@ var ts; function toSearchResult(value) { return value !== undefined ? { value: value } : undefined; } + function traceIfEnabled(state, diagnostic) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (state.traceEnabled) { + trace.apply(void 0, __spreadArray([state.host, diagnostic], args, false)); + } + } })(ts || (ts = {})); /* @internal */ var ts; @@ -49045,8 +49121,6 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; - IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; - IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var RecursionFlags; (function (RecursionFlags) { @@ -49465,6 +49539,12 @@ var ts; getOptionalType: function () { return optionalType; }, getPromiseType: function () { return getGlobalPromiseType(/*reportErrors*/ false); }, getPromiseLikeType: function () { return getGlobalPromiseLikeType(/*reportErrors*/ false); }, + getAsyncIterableType: function () { + var type = getGlobalAsyncIterableType(/*reportErrors*/ false); + if (type === emptyGenericType) + return undefined; + return type; + }, isSymbolAccessible: isSymbolAccessible, isArrayType: isArrayType, isTupleType: isTupleType, @@ -50302,9 +50382,9 @@ var ts; return symbol; } if (symbol.flags & 2097152 /* SymbolFlags.Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { + var targetFlags = getAllSymbolFlags(symbol); + // `targetFlags` will be `SymbolFlags.All` if an error occurred in alias resolution; this avoids cascading errors + if (targetFlags & meaning) { return symbol; } } @@ -50937,8 +51017,8 @@ var ts; !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) && + !checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; var suggestedLib = void 0; @@ -51025,7 +51105,7 @@ var ts; } } if (result && errorLocation && meaning & 111551 /* SymbolFlags.Value */ && result.flags & 2097152 /* SymbolFlags.Alias */ && !(result.flags & 111551 /* SymbolFlags.Value */) && !ts.isValidTypeOnlyAliasUseSite(errorLocation)) { - var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); + var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, 111551 /* SymbolFlags.Value */); if (typeOnlyDeclaration) { var message = typeOnlyDeclaration.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type @@ -51188,7 +51268,7 @@ var ts; return false; } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */)) { + if (meaning & 111551 /* SymbolFlags.Value */) { if (isPrimitiveTypeName(name)) { if (isExtendedByInterface(errorLocation)) { error(errorLocation, ts.Diagnostics.An_interface_cannot_extend_a_primitive_type_like_0_an_interface_can_only_extend_named_types_and_classes, ts.unescapeLeadingUnderscores(name)); @@ -51199,7 +51279,8 @@ var ts; return true; } var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); - if (symbol && !(symbol.flags & 1024 /* SymbolFlags.NamespaceModule */)) { + var allFlags = symbol && getAllSymbolFlags(symbol); + if (symbol && allFlags !== undefined && !(allFlags & 111551 /* SymbolFlags.Value */)) { var rawName = ts.unescapeLeadingUnderscores(name); if (isES2015OrLaterConstructorName(name)) { error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later, rawName); @@ -51247,16 +51328,16 @@ var ts; } return false; } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (111551 /* SymbolFlags.Value */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~788968 /* SymbolFlags.Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) { + if (meaning & (111551 /* SymbolFlags.Value */ & ~788968 /* SymbolFlags.Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* SymbolFlags.NamespaceModule */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); return true; } } - else if (meaning & (788968 /* SymbolFlags.Type */ & ~1024 /* SymbolFlags.NamespaceModule */ & ~111551 /* SymbolFlags.Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* SymbolFlags.ValueModule */ | 1024 /* SymbolFlags.NamespaceModule */) & ~788968 /* SymbolFlags.Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + else if (meaning & (788968 /* SymbolFlags.Type */ & ~111551 /* SymbolFlags.Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1536 /* SymbolFlags.Module */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol) { error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); return true; @@ -51846,6 +51927,52 @@ var ts; } return undefined; } + /** + * Gets combined flags of a `symbol` and all alias targets it resolves to. `resolveAlias` + * is typically recursive over chains of aliases, but stops mid-chain if an alias is merged + * with another exported symbol, e.g. + * ```ts + * // a.ts + * export const a = 0; + * // b.ts + * export { a } from "./a"; + * export type a = number; + * // c.ts + * import { a } from "./b"; + * ``` + * Calling `resolveAlias` on the `a` in c.ts would stop at the merged symbol exported + * from b.ts, even though there is still more alias to resolve. Consequently, if we were + * trying to determine if the `a` in c.ts has a value meaning, looking at the flags on + * the local symbol and on the symbol returned by `resolveAlias` is not enough. + * @returns SymbolFlags.All if `symbol` is an alias that ultimately resolves to `unknown`; + * combined flags of all alias targets otherwise. + */ + function getAllSymbolFlags(symbol) { + var flags = symbol.flags; + var seenSymbols; + while (symbol.flags & 2097152 /* SymbolFlags.Alias */) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return 67108863 /* SymbolFlags.All */; + } + // Optimizations - try to avoid creating or adding to + // `seenSymbols` if possible + if (target === symbol || (seenSymbols === null || seenSymbols === void 0 ? void 0 : seenSymbols.has(target))) { + break; + } + if (target.flags & 2097152 /* SymbolFlags.Alias */) { + if (seenSymbols) { + seenSymbols.add(target); + } + else { + seenSymbols = new ts.Set([symbol, target]); + } + } + flags |= target.flags; + symbol = target; + } + return flags; + } /** * Marks a symbol as type-only if its declaration is syntactically type-only. * If it is not itself marked type-only, but resolves to a type-only alias @@ -51891,19 +52018,25 @@ var ts; return !!aliasDeclarationLinks.typeOnlyDeclaration; } /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */ - function getTypeOnlyAliasDeclaration(symbol) { + function getTypeOnlyAliasDeclaration(symbol, include) { if (!(symbol.flags & 2097152 /* SymbolFlags.Alias */)) { return undefined; } var links = getSymbolLinks(symbol); - return links.typeOnlyDeclaration || undefined; + if (include === undefined) { + return links.typeOnlyDeclaration || undefined; + } + if (links.typeOnlyDeclaration) { + return getAllSymbolFlags(resolveAlias(links.typeOnlyDeclaration.symbol)) & include ? links.typeOnlyDeclaration : undefined; + } + return undefined; } function markExportAsReferenced(node) { var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target) { var markAlias = target === unknownSymbol || - ((target.flags & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol)); + ((getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)); if (markAlias) { markAliasSymbolAsReferenced(symbol); } @@ -51923,8 +52056,7 @@ var ts; // This way a chain of imports can be elided if ultimately the final input is only used in a type // position. if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveSymbol(symbol); - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(resolveSymbol(symbol)) & 111551 /* SymbolFlags.Value */) { // import foo = checkExpressionCached(node.moduleReference); } @@ -52746,7 +52878,7 @@ var ts; } function symbolIsValue(symbol, includeTypeOnlyMembers) { return !!(symbol.flags & 111551 /* SymbolFlags.Value */ || - symbol.flags & 2097152 /* SymbolFlags.Alias */ && resolveAlias(symbol).flags & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); + symbol.flags & 2097152 /* SymbolFlags.Alias */ && getAllSymbolFlags(symbol) & 111551 /* SymbolFlags.Value */ && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol))); } function findConstructorDeclaration(node) { var members = node.members; @@ -53015,8 +53147,10 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { + var shouldResolveAlias = (symbolFromSymbolTable.flags & 2097152 /* SymbolFlags.Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 278 /* SyntaxKind.ExportSpecifier */)); + symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + var flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags; + if (flags & meaning) { qualify = true; return true; } @@ -55328,7 +55462,7 @@ var ts; // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it var indices = ts.indicesOf(statements); var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); }); - if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) { + if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return ts.canHaveExportModifier(statements[i]); })) { for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) { var index_1 = associatedIndices_1[_i]; statements[index_1] = addExportModifier(statements[index_1]); @@ -55362,15 +55496,6 @@ var ts; } return statements; } - function canHaveExportModifier(node) { - return ts.isEnumDeclaration(node) || - ts.isVariableStatement(node) || - ts.isFunctionDeclaration(node) || - ts.isClassDeclaration(node) || - (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) || - ts.isInterfaceDeclaration(node) || - isTypeDeclaration(node); - } function addExportModifier(node) { var flags = (ts.getEffectiveModifierFlags(node) | 1 /* ModifierFlags.Export */) & ~2 /* ModifierFlags.Ambient */; return ts.factory.updateModifiers(node, flags); @@ -55617,7 +55742,7 @@ var ts; (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration); if (additionalModifierFlags & 1 /* ModifierFlags.Export */ && enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) && - canHaveExportModifier(node)) { + ts.canHaveExportModifier(node)) { // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private newModifierFlags |= 1 /* ModifierFlags.Export */; } @@ -55673,7 +55798,7 @@ var ts; return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { - return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* SymbolFlags.Value */); }); + return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(getAllSymbolFlags(resolveSymbol(m)) & 111551 /* SymbolFlags.Value */); }); } function serializeModule(symbol, symbolName, modifierFlags) { var members = getNamespaceMembersForSerialization(symbol); @@ -57893,7 +58018,7 @@ var ts; links.type = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType - : targetSymbol.flags & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) + : getAllSymbolFlags(targetSymbol) & 111551 /* SymbolFlags.Value */ ? getTypeOfSymbol(targetSymbol) : errorType; } return links.type; @@ -59776,7 +59901,20 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */ && getMappedTypeModifiers(type) & 4 /* MappedTypeModifiers.IncludeOptional */); } function isGenericMappedType(type) { - return !!(ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); + if (ts.getObjectFlags(type) & 32 /* ObjectFlags.Mapped */) { + var constraint = getConstraintTypeFromMappedType(type); + if (isGenericIndexType(constraint)) { + return true; + } + // A mapped type is generic if the 'as' clause references generic types other than the iteration type. + // To determine this, we substitute the constraint type (that we now know isn't generic) for the iteration + // type and check whether the resulting type is generic. + var nameType = getNameTypeFromMappedType(type); + if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type), constraint)))) { + return true; + } + } + return false; } function resolveStructuredTypeMembers(type) { if (!type.members) { @@ -60246,7 +60384,7 @@ var ts; var indexTypes; var isUnion = containingType.flags & 1048576 /* TypeFlags.Union */; // Flags we want to propagate to the result if they exist in all source symbols - var optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */; + var optionalFlag; var syntheticFlag = 4 /* CheckFlags.SyntheticMethod */; var checkFlags = isUnion ? 0 : 8 /* CheckFlags.Readonly */; var mergedInstantiations = false; @@ -60257,11 +60395,14 @@ var ts; var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop) { - if (isUnion) { - optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); - } - else { - optionalFlag &= prop.flags; + if (prop.flags & 106500 /* SymbolFlags.ClassMember */) { + optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : (optionalFlag = isUnion ? 0 /* SymbolFlags.None */ : 16777216 /* SymbolFlags.Optional */); + if (isUnion) { + optionalFlag |= (prop.flags & 16777216 /* SymbolFlags.Optional */); + } + else { + optionalFlag &= prop.flags; + } } if (!singleProp) { singleProp = prop; @@ -60380,7 +60521,7 @@ var ts; propTypes.push(type); } ts.addRange(propTypes, indexTypes); - var result = createSymbol(4 /* SymbolFlags.Property */ | optionalFlag, name, syntheticFlag | checkFlags); + var result = createSymbol(4 /* SymbolFlags.Property */ | (optionalFlag !== null && optionalFlag !== void 0 ? optionalFlag : 0), name, syntheticFlag | checkFlags); result.containingType = containingType; if (!hasNonUniformValueDeclaration && firstValueDeclaration) { result.valueDeclaration = firstValueDeclaration; @@ -63093,8 +63234,14 @@ var ts; return getStringLiteralType(text); } newTexts.push(text); - if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { - return stringType; + if (ts.every(newTexts, function (t) { return t === ""; })) { + if (ts.every(newTypes, function (t) { return !!(t.flags & 4 /* TypeFlags.String */); })) { + return stringType; + } + // Normalize `${Mapping}` into Mapping + if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) { + return newTypes[0]; + } } var id = "".concat(getTypeListId(newTypes), "|").concat(ts.map(newTexts, function (t) { return t.length; }).join(","), "|").concat(newTexts.join("")); var type = templateLiteralTypes.get(id); @@ -63153,12 +63300,14 @@ var ts; } function getStringMappingType(symbol, type) { return type.flags & (1048576 /* TypeFlags.Union */ | 131072 /* TypeFlags.Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) : - // Mapping> === Mapping - type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : - isGenericIndexType(type) || isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, isPatternLiteralPlaceholderType(type) && !(type.flags & 268435456 /* TypeFlags.StringMapping */) ? getTemplateLiteralType(["", ""], [type]) : type) : - type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : - type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : - type; + type.flags & 128 /* TypeFlags.StringLiteral */ ? getStringLiteralType(applyStringMapping(symbol, type.value)) : + type.flags & 134217728 /* TypeFlags.TemplateLiteral */ ? getTemplateLiteralType.apply(void 0, applyTemplateStringMapping(symbol, type.texts, type.types)) : + // Mapping> === Mapping + type.flags & 268435456 /* TypeFlags.StringMapping */ && symbol === type.symbol ? type : + type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 268435456 /* TypeFlags.StringMapping */) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) : + // This handles Mapping<`${number}`> and Mapping<`${bigint}`> + isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) : + type; } function applyStringMapping(symbol, str) { switch (intrinsicTypeKinds.get(symbol.escapedName)) { @@ -63323,7 +63472,18 @@ var ts; return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; } errorIfWritingToReadonlyIndex(indexInfo); - return accessFlags & 1 /* AccessFlags.IncludeUndefined */ ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type; + // When accessing an enum object with its own type, + // e.g. E[E.A] for enum E { A }, undefined shouldn't + // be included in the result type + if ((accessFlags & 1 /* AccessFlags.IncludeUndefined */) && + !(objectType.symbol && + objectType.symbol.flags & (256 /* SymbolFlags.RegularEnum */ | 128 /* SymbolFlags.ConstEnum */) && + (indexType.symbol && + indexType.flags & 1024 /* TypeFlags.EnumLiteral */ && + getParentOfSymbol(indexType.symbol) === objectType.symbol))) { + return getUnionType([indexInfo.type, undefinedType]); + } + return indexInfo.type; } if (indexType.flags & 131072 /* TypeFlags.Never */) { return neverType; @@ -63426,10 +63586,11 @@ var ts; accessNode; } function isPatternLiteralPlaceholderType(type) { - return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || !!(type.flags & 268435456 /* TypeFlags.StringMapping */ && isPatternLiteralPlaceholderType(type.type)); + return !!(type.flags & (1 /* TypeFlags.Any */ | 4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) || isPatternLiteralType(type); } function isPatternLiteralType(type) { - return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType); + return !!(type.flags & 134217728 /* TypeFlags.TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType) || + !!(type.flags & 268435456 /* TypeFlags.StringMapping */) && isPatternLiteralPlaceholderType(type.type); } function isGenericType(type) { return !!getGenericObjectFlags(type); @@ -63708,18 +63869,23 @@ var ts; var result; var extraTypes; var tailCount = 0; - var _loop_20 = function () { + // We loop here for an immediately nested conditional type in the false position, effectively treating + // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for + // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of + // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive + // cases we increment the tail recursion counter and stop after 1000 iterations. + while (true) { if (tailCount === 1000) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); result = errorType; - return "break"; + break; } var isUnwrapped = isTypicalNondistributiveConditional(root); var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, getActualTypeVariable(root.checkType)), mapper); var checkTypeInstantiable = isGenericType(checkType); var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper); if (checkType === wildcardType || extendsType === wildcardType) { - return { value: wildcardType }; + return wildcardType; } var combinedMapper = void 0; if (root.inferTypeParameters) { @@ -63752,11 +63918,7 @@ var ts; } } } - // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type - // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to - // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint - // so in those cases we refain from performing inference and retain the uninfered type parameter - if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -63788,14 +63950,14 @@ var ts; var newRoot = falseType_1.root; if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) { root = newRoot; - return "continue"; + continue; } if (canTailRecurse(falseType_1, mapper)) { - return "continue"; + continue; } } result = instantiateType(falseType_1, mapper); - return "break"; + break; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -63806,10 +63968,10 @@ var ts; var trueType_1 = getTypeFromTypeNode(root.node.trueType); var trueMapper = combinedMapper || mapper; if (canTailRecurse(trueType_1, trueMapper)) { - return "continue"; + continue; } result = instantiateType(trueType_1, trueMapper); - return "break"; + break; } } // Return a deferred type for a check that is neither definitely true nor definitely false @@ -63821,19 +63983,7 @@ var ts; result.combinedMapper = combinedMapper; result.aliasSymbol = aliasSymbol || root.aliasSymbol; result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 - return "break"; - }; - // We loop here for an immediately nested conditional type in the false position, effectively treating - // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for - // purposes of resolution. We also loop here when resolution of a conditional type ends in resolution of - // another (or, through recursion, possibly the same) conditional type. In the potentially tail-recursive - // cases we increment the tail recursion counter and stop after 1000 iterations. - while (true) { - var state_6 = _loop_20(); - if (typeof state_6 === "object") - return state_6.value; - if (state_6 === "break") - break; + break; } return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; // We tail-recurse for generic conditional types that (a) have not already been evaluated and cached, and @@ -66287,7 +66437,7 @@ var ts; return 0 /* Ternary.False */; } } - var isPerformingCommonPropertyChecks = (relation !== comparableRelation || !(source.flags & 1048576 /* TypeFlags.Union */) && isLiteralType(source)) && + var isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source)) && !(intersectionState & 2 /* IntersectionState.Target */) && source.flags & (131068 /* TypeFlags.Primitive */ | 524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && source !== globalObjectType && target.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) && isWeakType(target) && @@ -66315,27 +66465,6 @@ var ts; var result_7 = skipCaching ? unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) : recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags); - // For certain combinations involving intersections and optional, excess, or mismatched properties we need - // an extra property check where the intersection is viewed as a single object. The following are motivating - // examples that all should be errors, but aren't without this extra property check: - // - // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property - // - // declare let wrong: { a: { y: string } }; - // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type - // - // function foo(x: { a?: string }, y: T & { a: boolean }) { - // x = y; // Mismatched property in source intersection - // } - // - // We suppress recursive intersection property checks because they can generate lots of work when relating - // recursive intersections that are structurally similar but not exactly identical. See #37854. - if (result_7 && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { - inPropertyCheck = true; - result_7 &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* IntersectionState.PropertyCheck */, recursionFlags); - inPropertyCheck = false; - } if (result_7) { return result_7; } @@ -66447,7 +66576,7 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* TypeFlags.Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_21 = function (prop) { + var _loop_20 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { @@ -66510,9 +66639,9 @@ var ts; }; for (var _i = 0, _b = getPropertiesOfType(source); _i < _b.length; _i++) { var prop = _b[_i]; - var state_7 = _loop_21(prop); - if (typeof state_7 === "object") - return state_7.value; + var state_6 = _loop_20(prop); + if (typeof state_6 === "object") + return state_6.value; } return false; } @@ -66733,8 +66862,7 @@ var ts; if (overflow) { return 0 /* Ternary.False */; } - var keyIntersectionState = intersectionState | (inPropertyCheck ? 8 /* IntersectionState.InPropertyCheck */ : 0); - var id = getRelationKey(source, target, keyIntersectionState, relation, /*ingnoreConstraints*/ false); + var id = getRelationKey(source, target, intersectionState, relation, /*ingnoreConstraints*/ false); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* RelationComparisonResult.Failed */ && !(entry & 4 /* RelationComparisonResult.Reported */)) { @@ -66764,7 +66892,7 @@ var ts; // A key that starts with "*" is an indication that we have type references that reference constrained // type parameters. For such keys we also check against the key we would have gotten if all type parameters // were unconstrained. - var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, keyIntersectionState, relation, /*ignoreConstraints*/ true) : undefined; + var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, intersectionState, relation, /*ignoreConstraints*/ true) : undefined; for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { @@ -66851,7 +66979,7 @@ var ts; function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { var saveErrorInfo = captureErrorCalculationState(); var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo); - if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + if (relation !== identityRelation) { // The combined constraint of an intersection type is the intersection of the constraints of // the constituents. When an intersection type contains instantiable types with union type // constraints, there are situations where we need to examine the combined constraint. One is @@ -66865,10 +66993,33 @@ var ts; // needs to have its constraint hoisted into an intersection with said type parameter, this way // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` - var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); - if (constraint && !(constraint.flags & 131072 /* TypeFlags.Never */) && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself - // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this - result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (!result && (source.flags & 2097152 /* TypeFlags.Intersection */ || source.flags & 262144 /* TypeFlags.TypeParameter */ && target.flags & 1048576 /* TypeFlags.Union */)) { + var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* TypeFlags.Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* TypeFlags.Union */)); + if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself + // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this + result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + } + } + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* TypeFlags.Intersection */ && !isGenericObjectType(target) && source.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */) || + isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & 2097152 /* TypeFlags.Intersection */ && getApparentType(source).flags & 3670016 /* TypeFlags.StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* ObjectFlags.NonInferrableType */); }))) { + inPropertyCheck = true; + result &= propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); + inPropertyCheck = false; } } if (result) { @@ -66877,9 +67028,6 @@ var ts; return result; } function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo) { - if (intersectionState & 4 /* IntersectionState.PropertyCheck */) { - return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* IntersectionState.None */); - } var result; var originalErrorInfo; var varianceCheckFailed = false; @@ -66980,7 +67128,7 @@ var ts; // with another type parameter unless one extends the other. (Remember: comparability is mostly bidirectional!) var constraint = getConstraintOfTypeParameter(source); if (constraint && hasNonCircularBaseConstraint(source)) { - while (constraint && constraint.flags & 262144 /* TypeFlags.TypeParameter */) { + while (constraint && someType(constraint, function (c) { return !!(c.flags & 262144 /* TypeFlags.TypeParameter */); })) { if (result = isRelatedTo(constraint, target, 1 /* RecursionFlags.Source */, /*reportErrors*/ false)) { return result; } @@ -67503,11 +67651,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_22 = function (combination) { + var _loop_21 = function (combination) { var hasMatch = false; outer: for (var _c = 0, _d = target.types; _c < _d.length; _c++) { var type = _d[_c]; - var _loop_23 = function (i) { + var _loop_22 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -67523,8 +67671,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_9 = _loop_23(i); - switch (state_9) { + var state_8 = _loop_22(i); + switch (state_8) { case "continue-outer": continue outer; } } @@ -67537,9 +67685,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_8 = _loop_22(combination); - if (typeof state_8 === "object") - return state_8.value; + var state_7 = _loop_21(combination); + if (typeof state_7 === "object") + return state_7.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* Ternary.True */; @@ -67636,7 +67784,7 @@ var ts; return 0 /* Ternary.False */; } // When checking for comparability, be more lenient with optional properties. - if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* SymbolFlags.Optional */ && targetProp.flags & 106500 /* SymbolFlags.ClassMember */ && !(targetProp.flags & 16777216 /* SymbolFlags.Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -68244,7 +68392,7 @@ var ts; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* tracing.Phase.CheckTypes */, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); links.variances = ts.emptyArray; var variances = []; - var _loop_24 = function (tp) { + var _loop_23 = function (tp) { var modifiers = getVarianceModifiers(tp); var variance = modifiers & 65536 /* ModifierFlags.Out */ ? modifiers & 32768 /* ModifierFlags.In */ ? 0 /* VarianceFlags.Invariant */ : 1 /* VarianceFlags.Covariant */ : @@ -68282,7 +68430,7 @@ var ts; }; for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { var tp = typeParameters_2[_i]; - _loop_24(tp); + _loop_23(tp); } links.variances = variances; ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop({ variances: variances.map(ts.Debug.formatVariance) }); @@ -68736,8 +68884,7 @@ var ts; return !!(type.flags & 109440 /* TypeFlags.Unit */); } function isUnitLikeType(type) { - return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.some(type.types, isUnitType) : - !!(type.flags & 109440 /* TypeFlags.Unit */); + return isUnitType(getBaseConstraintOrType(type)); } function extractUnitType(type) { return type.flags & 2097152 /* TypeFlags.Intersection */ ? ts.find(type.types, isUnitType) || type : type; @@ -69616,7 +69763,7 @@ var ts; && (!roundTripOnly || s === ts.pseudoBigIntToString({ negative: negative, base10Value: ts.parsePseudoBigInt(scanner.getTokenValue()) })); } function isMemberOfStringMapping(source, target) { - if (target.flags & (4 /* TypeFlags.String */ | 3 /* TypeFlags.AnyOrUnknown */)) { + if (target.flags & (4 /* TypeFlags.String */ | 1 /* TypeFlags.Any */)) { return true; } if (target.flags & 134217728 /* TypeFlags.TemplateLiteral */) { @@ -70240,7 +70387,7 @@ var ts; // upon instantiation, would collapse all the placeholders to just 'string', and an assignment check might // succeed. That would be a pointless and confusing outcome. if (matches || ts.every(target.texts, function (s) { return s.length === 0; })) { - var _loop_25 = function (i) { + var _loop_24 = function (i) { var source_1 = matches ? matches[i] : neverType; var target_3 = types[i]; // If we are inferring from a string literal type to a type variable whose constraint includes one of the @@ -70290,7 +70437,7 @@ var ts; inferFromTypes(source_1, target_3); }; for (var i = 0; i < types.length; i++) { - _loop_25(i); + _loop_24(i); } } } @@ -70742,7 +70889,7 @@ var ts; } if (ts.isEntityNameExpression(node.argumentExpression)) { var symbol = resolveEntityName(node.argumentExpression, 111551 /* SymbolFlags.Value */, /*ignoreErrors*/ true); - if (!symbol || !isConstVariable(symbol)) + if (!symbol || !(isConstVariable(symbol) || (symbol.flags & 8 /* SymbolFlags.EnumMember */))) return undefined; var declaration = symbol.valueDeclaration; if (declaration === undefined) @@ -70756,7 +70903,12 @@ var ts; } if (ts.hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node.argumentExpression)) { var initializer = ts.getEffectiveInitializer(declaration); - return initializer && tryGetNameFromType(getTypeOfExpression(initializer)); + if (initializer) { + return tryGetNameFromType(getTypeOfExpression(initializer)); + } + if (ts.isEnumMember(declaration)) { + return ts.getTextOfPropertyName(declaration.name); + } } } return undefined; @@ -70814,7 +70966,7 @@ var ts; function mapTypesByKeyProperty(types, name) { var map = new ts.Map(); var count = 0; - var _loop_26 = function (type) { + var _loop_25 = function (type) { if (type.flags & (524288 /* TypeFlags.Object */ | 2097152 /* TypeFlags.Intersection */ | 58982400 /* TypeFlags.InstantiableNonPrimitive */)) { var discriminant = getTypeOfPropertyOfType(type, name); if (discriminant) { @@ -70840,9 +70992,9 @@ var ts; }; for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { var type = types_15[_i]; - var state_10 = _loop_26(type); - if (typeof state_10 === "object") - return state_10.value; + var state_9 = _loop_25(type); + if (typeof state_9 === "object") + return state_9.value; } return count >= 10 && count * 2 >= types.length ? map : undefined; } @@ -71439,6 +71591,7 @@ var ts; ts.isInJSFile(node) && ts.hasInitializer(node) && node.initializer && ts.isFunctionExpressionOrArrowFunction(node.initializer) && ts.getEffectiveReturnTypeNode(node.initializer)); } function getExplicitTypeOfSymbol(symbol, diagnostic) { + symbol = resolveSymbol(symbol); if (symbol.flags & (16 /* SymbolFlags.Function */ | 8192 /* SymbolFlags.Method */ | 32 /* SymbolFlags.Class */ | 512 /* SymbolFlags.ValueModule */)) { return getTypeOfSymbol(symbol); } @@ -71477,7 +71630,7 @@ var ts; switch (node.kind) { case 79 /* SyntaxKind.Identifier */: var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); - return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol, diagnostic); + return getExplicitTypeOfSymbol(symbol, diagnostic); case 108 /* SyntaxKind.ThisKeyword */: return getExplicitThisType(node); case 106 /* SyntaxKind.SuperKeyword */: @@ -71964,7 +72117,7 @@ var ts; type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (expr.kind === 218 /* SyntaxKind.TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { - type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else { if (strictNullChecks) { @@ -72245,7 +72398,7 @@ var ts; !!(prop.flags & 16777216 /* SymbolFlags.Optional */) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue; } - function narrowByInKeyword(type, nameType, assumeTrue) { + function narrowTypeByInKeyword(type, nameType, assumeTrue) { var name = getPropertyNameFromType(nameType); var isKnownProperty = someType(type, function (t) { return isTypePresencePossible(t, name, /*assumeTrue*/ true); }); if (isKnownProperty) { @@ -72326,7 +72479,7 @@ var ts; return getTypeWithFacts(type, assumeTrue ? 524288 /* TypeFacts.NEUndefined */ : 65536 /* TypeFacts.EQUndefined */); } if (isMatchingReference(reference, target)) { - return narrowByInKeyword(type, leftType, assumeTrue); + return narrowTypeByInKeyword(type, leftType, assumeTrue); } } break; @@ -72515,7 +72668,7 @@ var ts; neverType; }); } - function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { + function narrowTypeBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { var witnesses = getSwitchClauseTypeOfWitnesses(switchStatement); if (!witnesses) { return type; @@ -72903,15 +73056,15 @@ var ts; }); } function markAliasReferenced(symbol, location) { - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { var target = resolveAlias(symbol); - if (target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */)) { // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled // (because the const enum value will not be inlined), or if (2) the alias is an export // of a const enum declaration that will be preserved. if (compilerOptions.isolatedModules || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || - !isConstEnumOrConstEnumOnlyModule(target)) { + !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); } else { @@ -73139,7 +73292,7 @@ var ts; // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* TypeFlags.AnyOrUnknown */ | 16384 /* TypeFlags.Void */)) !== 0 || isInTypeQuery(node) || node.parent.kind === 278 /* SyntaxKind.ExportSpecifier */) || node.parent.kind === 232 /* SyntaxKind.NonNullExpression */ || @@ -73168,6 +73321,12 @@ var ts; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; } + function isSameScopedBindingElement(node, declaration) { + if (ts.isBindingElement(declaration)) { + var bindingElement = ts.findAncestor(node, ts.isBindingElement); + return bindingElement && ts.getRootDeclaration(bindingElement) === ts.getRootDeclaration(declaration); + } + } function shouldMarkIdentifierAliasReferenced(node) { var _a; var parent = node.parent; @@ -73509,12 +73668,17 @@ var ts; var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var container = immediateContainer; var needToCaptureLexicalThis = false; + var inAsyncFunction = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { while (container && container.kind === 216 /* SyntaxKind.ArrowFunction */) { + if (ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ScriptTarget.ES2015 */; } + if (container && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) + inAsyncFunction = true; } var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; @@ -73620,12 +73784,12 @@ var ts; // as a call expression cannot be used as the target of a destructuring assignment while a property access can. // // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations. - if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && ts.hasSyntacticModifier(container, 512 /* ModifierFlags.Async */)) { + if (container.kind === 171 /* SyntaxKind.MethodDeclaration */ && inAsyncFunction) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */; + getNodeLinks(container).flags |= 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */; } else { - getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.AsyncMethodWithSuper */; + getNodeLinks(container).flags |= 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */; } } if (needToCaptureLexicalThis) { @@ -74321,9 +74485,10 @@ var ts; function instantiateContextualType(contextualType, node, contextFlags) { if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* TypeFlags.Instantiable */)) { var inferenceContext = getInferenceContext(node); - // If no inferences have been made, nothing is gained from instantiating as type parameters - // would just be replaced with their defaults similar to the apparent type. - if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidates)) { + // If no inferences have been made, and none of the type parameters for which we are inferring + // specify default types, nothing is gained from instantiating as type parameters would just be + // replaced with their constraints similar to the apparent type. + if (inferenceContext && contextFlags & 1 /* ContextFlags.Signature */ && ts.some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) { // For contextual signatures we incorporate all inferences made so far, e.g. from return // types as well as arguments to the left in a function call. return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper); @@ -77297,7 +77462,7 @@ var ts; if (spreadIndex >= 0) { // Create synthetic arguments from spreads of tuple types. var effectiveArgs_1 = args.slice(0, spreadIndex); - var _loop_27 = function (i) { + var _loop_26 = function (i) { var arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. var spreadType = arg.kind === 227 /* SyntaxKind.SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); @@ -77314,7 +77479,7 @@ var ts; } }; for (var i = spreadIndex; i < args.length; i++) { - _loop_27(i); + _loop_26(i); } return effectiveArgs_1; } @@ -77643,7 +77808,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_28 = function (c) { + var _loop_27 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* CheckMode.Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -77661,7 +77826,7 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_28(c); + _loop_27(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); @@ -77819,7 +77984,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_29 = function (i) { + var _loop_28 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -77827,7 +77992,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_29(i); + _loop_28(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* SignatureFlags.None */; @@ -78797,7 +78962,7 @@ var ts; if (symbol && symbol.flags & 2097152 /* SymbolFlags.Alias */) { symbol = resolveAlias(symbol); } - return !!(symbol && (symbol.flags & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); + return !!(symbol && (getAllSymbolFlags(symbol) & 384 /* SymbolFlags.Enum */) && getEnumKind(symbol) === 1 /* EnumKind.Literal */); } return false; } @@ -79459,7 +79624,17 @@ var ts; } function isExhaustiveSwitchStatement(node) { var links = getNodeLinks(node); - return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node)); + if (links.isExhaustive === undefined) { + links.isExhaustive = 0; // Indicate resolution is in process + var exhaustive = computeExhaustiveSwitchStatement(node); + if (links.isExhaustive === 0) { + links.isExhaustive = exhaustive; + } + } + else if (links.isExhaustive === 0) { + links.isExhaustive = false; // Resolve circularity to false + } + return links.isExhaustive; } function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 218 /* SyntaxKind.TypeOfExpression */) { @@ -79467,7 +79642,7 @@ var ts; if (!witnesses) { return false; } - var operandConstraint = getBaseConstraintOrType(getTypeOfExpression(node.expression.expression)); + var operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression)); // Get the not-equal flags for all handled cases. var notEqualFacts_2 = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); if (operandConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */) { @@ -79477,7 +79652,7 @@ var ts; // A missing not-equal flag indicates that the type wasn't handled by some case. return !someType(operandConstraint, function (t) { return (getTypeFacts(t) & notEqualFacts_2) === notEqualFacts_2; }); } - var type = getTypeOfExpression(node.expression); + var type = checkExpressionCached(node.expression); if (!isLiteralType(type)) { return false; } @@ -81171,6 +81346,9 @@ var ts; function hasInferenceCandidates(info) { return !!(info.candidates || info.contraCandidates); } + function hasInferenceCandidatesOrDefault(info) { + return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter)); + } function hasOverlappingInferences(a, b) { for (var i = 0; i < a.length; i++) { if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) { @@ -81872,7 +82050,7 @@ var ts; var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol === null || indexSymbol === void 0 ? void 0 : indexSymbol.declarations) { var indexSignatureMap_1 = new ts.Map(); - var _loop_30 = function (declaration) { + var _loop_29 = function (declaration) { if (declaration.parameters.length === 1 && declaration.parameters[0].type) { forEachType(getTypeFromTypeNode(declaration.parameters[0].type), function (type) { var entry = indexSignatureMap_1.get(getTypeId(type)); @@ -81887,7 +82065,7 @@ var ts; }; for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - _loop_30(declaration); + _loop_29(declaration); } indexSignatureMap_1.forEach(function (entry) { if (entry.declarations.length > 1) { @@ -82164,7 +82342,7 @@ var ts; } var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { - if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { + if (ts.some(symbol.declarations, function (d) { return ts.isTypeDeclaration(d) && !!(d.flags & 268435456 /* NodeFlags.Deprecated */); })) { addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName); } if (type.flags & 32 /* TypeFlags.Enum */ && symbol.flags & 8 /* SymbolFlags.EnumMember */) { @@ -82767,7 +82945,7 @@ var ts; return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; } // primitives with a `{ then() }` won't be unwrapped/adopted. - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217 @@ -82834,7 +83012,7 @@ var ts; * Determines whether a type is an object with a callable `then` member. */ function isThenableType(type) { - if (allTypesAssignableToKind(type, 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { + if (allTypesAssignableToKind(getBaseConstraintOrType(type), 131068 /* TypeFlags.Primitive */ | 131072 /* TypeFlags.Never */)) { // primitive types cannot be considered "thenable" since they are not objects. return false; } @@ -82868,7 +83046,7 @@ var ts; // We only need `Awaited` if `T` is a type variable that has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`, // or is promise-like. if (baseConstraint ? - baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint) : + baseConstraint.flags & 3 /* TypeFlags.AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : maybeTypeOfKind(type, 8650752 /* TypeFlags.TypeVariable */)) { return true; } @@ -83542,7 +83720,7 @@ var ts; } function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + var message = ts.isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; addDiagnostic(declaration, 0 /* UnusedKind.Local */, ts.createDiagnosticForNode(node, message, name)); } function isIdentifierThatStartsWithUnderscore(node) { @@ -84972,7 +85150,16 @@ var ts; var message = allowAsyncIterables ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator; - return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type)); + var suggestAwait = + // for (const x of Promise<...>) or [...Promise<...>] + !!getAwaitedTypeOfPromise(type) + // for (const x of AsyncIterable<...>) + || (!allowAsyncIterables && + ts.isForOfStatement(errorNode.parent) && + errorNode.parent.expression === errorNode && + getGlobalAsyncIterableType(/** reportErrors */ false) !== emptyGenericType && + isTypeAssignableTo(type, getGlobalAsyncIterableType(/** reportErrors */ false))); + return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } /** * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type. @@ -85487,7 +85674,7 @@ var ts; var propDeclaration = declaration && declaration.kind === 223 /* SyntaxKind.BinaryExpression */ || name && name.kind === 164 /* SyntaxKind.ComputedPropertyName */ ? declaration : undefined; var localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : undefined; - var _loop_31 = function (info) { + var _loop_30 = function (info) { var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; // We check only when (a) the property is declared in the containing type, or (b) the applicable index signature is declared // in the containing type, or (c) the containing type is an interface and no base interface contains both the property and @@ -85504,7 +85691,7 @@ var ts; }; for (var _i = 0, indexInfos_9 = indexInfos; _i < indexInfos_9.length; _i++) { var info = indexInfos_9[_i]; - _loop_31(info); + _loop_30(info); } } function checkIndexConstraintForIndexSignature(type, checkInfo) { @@ -85512,7 +85699,7 @@ var ts; var indexInfos = getApplicableIndexInfos(type, checkInfo.keyType); var interfaceDeclaration = ts.getObjectFlags(type) & 2 /* ObjectFlags.Interface */ ? ts.getDeclarationOfKind(type.symbol, 261 /* SyntaxKind.InterfaceDeclaration */) : undefined; var localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfNode(declaration)) === type.symbol ? declaration : undefined; - var _loop_32 = function (info) { + var _loop_31 = function (info) { if (info === checkInfo) return "continue"; var localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfNode(info.declaration)) === type.symbol ? info.declaration : undefined; @@ -85527,7 +85714,7 @@ var ts; }; for (var _i = 0, indexInfos_10 = indexInfos; _i < indexInfos_10.length; _i++) { var info = indexInfos_10[_i]; - _loop_32(info); + _loop_31(info); } } function checkTypeNameIsReserved(name, message) { @@ -85582,7 +85769,7 @@ var ts; } else { ts.forEach(jsdocParameters, function (_a, index) { - var name = _a.name; + var name = _a.name, isNameFirst = _a.isNameFirst; if (excludedParameters.has(index) || ts.isIdentifier(name) && parameters.has(name.escapedText)) { return; } @@ -85592,7 +85779,9 @@ var ts; } } else { - errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + if (!isNameFirst) { + errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + } } }); } @@ -85847,7 +86036,7 @@ var ts; 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 _loop_33 = function (member) { + var _loop_32 = function (member) { if (ts.hasAmbientModifier(member)) { return "continue"; } @@ -85864,7 +86053,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_33(member); + _loop_32(member); } } /** @@ -85952,7 +86141,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_34 = function (member) { + var _loop_33 = function (member) { if (ts.isStatic(member)) { return "continue"; } @@ -85971,7 +86160,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_34(member); + _loop_33(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -86042,7 +86231,7 @@ var ts; var _a, _b, _c, _d; // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfType(baseType); - var _loop_35 = function (baseProperty) { + var _loop_34 = function (baseProperty) { var base = getTargetSymbol(baseProperty); if (base.flags & 4194304 /* SymbolFlags.Prototype */) { return "continue"; @@ -86152,8 +86341,8 @@ var ts; }; basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { var baseProperty = baseProperties_1[_i]; - var state_11 = _loop_35(baseProperty); - switch (state_11) { + var state_10 = _loop_34(baseProperty); + switch (state_10) { case "continue-basePropertyCheck": continue basePropertyCheck; } } @@ -86672,12 +86861,11 @@ var ts; } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { - var _a; switch (node.kind) { case 240 /* SyntaxKind.VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _b = node.declarationList.declarations; _i < _b.length; _i++) { - var decl = _b[_i]; + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; @@ -86693,8 +86881,8 @@ var ts; case 257 /* SyntaxKind.VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { - for (var _c = 0, _d = name.elements; _c < _d.length; _c++) { - var el = _d[_c]; + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; // mark individual names in binding pattern checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -86710,18 +86898,6 @@ var ts; if (isGlobalAugmentation) { return; } - var symbol = getSymbolOfNode(node); - if (symbol) { - // module augmentations cannot introduce new names on the top level scope of the module - // this is done it two steps - // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error - // 2. main check - report error if value declaration of the parent symbol is module augmentation) - var reportError = !(symbol.flags & 33554432 /* SymbolFlags.Transient */); - if (!reportError) { - // symbol should not originate in augmentation - reportError = !!((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.declarations) && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } break; } } @@ -86823,10 +86999,11 @@ var ts; } return; } + var targetFlags = getAllSymbolFlags(target); var excludedMeanings = (symbol.flags & (111551 /* SymbolFlags.Value */ | 1048576 /* SymbolFlags.ExportValue */) ? 111551 /* SymbolFlags.Value */ : 0) | (symbol.flags & 788968 /* SymbolFlags.Type */ ? 788968 /* SymbolFlags.Type */ : 0) | (symbol.flags & 1920 /* SymbolFlags.Namespace */ ? 1920 /* SymbolFlags.Namespace */ : 0); - if (target.flags & excludedMeanings) { + if (targetFlags & excludedMeanings) { var message = node.kind === 278 /* SyntaxKind.ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; @@ -86836,7 +87013,7 @@ var ts; && !ts.isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 16777216 /* NodeFlags.Ambient */)) { var typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol); - var isType = !(target.flags & 111551 /* SymbolFlags.Value */); + var isType = !(targetFlags & 111551 /* SymbolFlags.Value */); if (isType || typeOnlyAlias) { switch (node.kind) { case 270 /* SyntaxKind.ImportClause */: @@ -86996,14 +87173,15 @@ var ts; if (node.moduleReference.kind !== 280 /* SyntaxKind.ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { - if (target.flags & 111551 /* SymbolFlags.Value */) { + var targetFlags = getAllSymbolFlags(target); + if (targetFlags & 111551 /* SymbolFlags.Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* SymbolFlags.Value */ | 1920 /* SymbolFlags.Namespace */).flags & 1920 /* SymbolFlags.Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } } - if (target.flags & 788968 /* SymbolFlags.Type */) { + if (targetFlags & 788968 /* SymbolFlags.Type */) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); } } @@ -87142,7 +87320,7 @@ var ts; markExportAsReferenced(node); } var target = symbol && (symbol.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(symbol) : symbol); - if (!target || target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (!target || getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { checkExpressionCached(node.propertyName || node.name); } } @@ -87189,7 +87367,7 @@ var ts; markAliasReferenced(sym, id); // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`) var target = sym.flags & 2097152 /* SymbolFlags.Alias */ ? resolveAlias(sym) : sym; - if (target === unknownSymbol || target.flags & 111551 /* SymbolFlags.Value */) { + if (getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */) { // However if it is a value, we need to check it's being used correctly checkExpressionCached(node.expression); } @@ -87861,29 +88039,9 @@ var ts; } function isTypeDeclarationName(name) { return name.kind === 79 /* SyntaxKind.Identifier */ && - isTypeDeclaration(name.parent) && + ts.isTypeDeclaration(name.parent) && ts.getNameOfDeclaration(name.parent) === name; } - function isTypeDeclaration(node) { - switch (node.kind) { - case 165 /* SyntaxKind.TypeParameter */: - case 260 /* SyntaxKind.ClassDeclaration */: - case 261 /* SyntaxKind.InterfaceDeclaration */: - case 262 /* SyntaxKind.TypeAliasDeclaration */: - case 263 /* SyntaxKind.EnumDeclaration */: - case 348 /* SyntaxKind.JSDocTypedefTag */: - case 341 /* SyntaxKind.JSDocCallbackTag */: - case 342 /* SyntaxKind.JSDocEnumTag */: - return true; - case 270 /* SyntaxKind.ImportClause */: - return node.isTypeOnly; - case 273 /* SyntaxKind.ImportSpecifier */: - case 278 /* SyntaxKind.ExportSpecifier */: - return node.parent.parent.isTypeOnly; - default: - return false; - } - } // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node) { while (node.parent.kind === 163 /* SyntaxKind.QualifiedName */) { @@ -88316,7 +88474,7 @@ var ts; var baseType = ts.firstOrUndefined(getBaseTypes(classType)); return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType; } - if (isTypeDeclaration(node)) { + if (ts.isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration var symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); @@ -88511,7 +88669,7 @@ var ts; return symbolLinks.exportsSomeValue; function isValue(s) { s = resolveSymbol(s); - return s && !!(s.flags & 111551 /* SymbolFlags.Value */); + return s && !!(getAllSymbolFlags(s) & 111551 /* SymbolFlags.Value */); } } function isNameOfModuleOrEnumDeclaration(node) { @@ -88564,7 +88722,7 @@ var ts; var symbol = getReferencedValueOrAliasSymbol(node); // We should only get the declaration of an alias if there isn't a local value // declaration for the symbol - if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol)) { + if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* SymbolFlags.Value */) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */)) { return getDeclarationOfAliasSymbol(symbol); } } @@ -88652,7 +88810,7 @@ var ts; case 273 /* SyntaxKind.ImportSpecifier */: case 278 /* SyntaxKind.ExportSpecifier */: var symbol = getSymbolOfNode(node); - return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol); + return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* SymbolFlags.Value */); case 275 /* SyntaxKind.ExportDeclaration */: var exportClause = node.exportClause; return !!exportClause && (ts.isNamespaceExport(exportClause) || @@ -88674,6 +88832,7 @@ var ts; return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); } function isAliasResolvedToValue(symbol) { + var _a; if (!symbol) { return false; } @@ -88683,7 +88842,7 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return !!(target.flags & 111551 /* SymbolFlags.Value */) && + return !!(((_a = getAllSymbolFlags(target)) !== null && _a !== void 0 ? _a : -1) & 111551 /* SymbolFlags.Value */) && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { @@ -88698,7 +88857,7 @@ var ts; } var target = getSymbolLinks(symbol).aliasTarget; // TODO: GH#18217 if (target && ts.getEffectiveModifierFlags(node) & 1 /* ModifierFlags.Export */ && - target.flags & 111551 /* SymbolFlags.Value */ && + getAllSymbolFlags(target) & 111551 /* SymbolFlags.Value */ && (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) { // An `export import ... =` of a value symbol is always considered referenced return true; @@ -98352,8 +98511,11 @@ var ts; } return ts.visitEachChild(node, visitor, context); case 174 /* SyntaxKind.GetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitGetAccessorDeclaration, node); case 175 /* SyntaxKind.SetAccessor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitSetAccessorDeclaration, node); case 173 /* SyntaxKind.Constructor */: + return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitConstructorDeclaration, node); case 260 /* SyntaxKind.ClassDeclaration */: case 228 /* SyntaxKind.ClassExpression */: return doWithContext(1 /* ContextFlags.NonTopLevel */ | 2 /* ContextFlags.HasLexicalThis */, visitDefault, node); @@ -98454,6 +98616,9 @@ var ts; return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression( /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } + function visitConstructorDeclaration(node) { + return factory.updateConstructorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); + } /** * Visits a MethodDeclaration node. * @@ -98468,7 +98633,14 @@ var ts; /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* FunctionFlags.Async */ ? transformAsyncFunctionBody(node) - : ts.visitFunctionBody(node.body, visitor, context)); + : transformMethodBody(node)); + } + function visitGetAccessorDeclaration(node) { + return factory.updateGetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), + /*type*/ undefined, transformMethodBody(node)); + } + function visitSetAccessorDeclaration(node) { + return factory.updateSetAccessorDeclaration(node, ts.visitNodes(node.modifiers, visitor, ts.isModifierLike), node.name, ts.visitParameterList(node.parameters, visitor, context), transformMethodBody(node)); } /** * Visits a FunctionDeclaration node. @@ -98582,6 +98754,42 @@ var ts; } return false; } + function transformMethodBody(node) { + ts.Debug.assertIsDefined(node.body); + var savedCapturedSuperProperties = capturedSuperProperties; + var savedHasSuperElementAccess = hasSuperElementAccess; + capturedSuperProperties = new ts.Set(); + hasSuperElementAccess = false; + var updated = ts.visitFunctionBody(node.body, visitor, context); + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + var originalMethod = ts.getOriginalNode(node, ts.isFunctionLikeDeclaration); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && + resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) && + (ts.getFunctionFlags(originalMethod) & 3 /* FunctionFlags.AsyncGenerator */) !== 3 /* FunctionFlags.AsyncGenerator */; + if (emitSuperHelpers) { + enableSubstitutionForAsyncMethodsWithSuper(); + if (capturedSuperProperties.size) { + var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + var statements = updated.statements.slice(); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + updated = factory.updateBlock(updated, statements); + } + if (hasSuperElementAccess) { + // Emit helpers for super element access expressions (`super[x]`). + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { + ts.addEmitHelper(updated, ts.advancedAsyncSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { + ts.addEmitHelper(updated, ts.asyncSuperHelper); + } + } + } + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + return updated; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -98614,7 +98822,7 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { @@ -98627,10 +98835,10 @@ var ts; ts.setTextRange(block, node.body); if (emitSuperHelpers && hasSuperElementAccess) { // Emit helpers for super element access expressions (`super[x]`). - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -98702,7 +98910,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ES2017SubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -98779,7 +98987,7 @@ var ts; || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* GeneratedIdentifierFlags.Optimistic */ | 32 /* GeneratedIdentifierFlags.FileLevel */), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -98794,7 +99002,7 @@ var ts; function createSuperAccessVariableStatement(factory, resolver, node, names) { // Create a variable declaration with a getter/setter (if binding) definition for each name: // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); - var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) !== 0; + var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) !== 0; var accessors = []; names.forEach(function (_, key) { var name = ts.unescapeLeadingUnderscores(key); @@ -99287,11 +99495,22 @@ var ts; } return node; } - function convertForOfStatementHead(node, boundValue) { - var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue); + function convertForOfStatementHead(node, boundValue, nonUserCode) { + var value = factory.createTempVariable(hoistVariableDeclaration); + var iteratorValueExpression = factory.createAssignment(value, boundValue); + var iteratorValueStatement = factory.createExpressionStatement(iteratorValueExpression); + ts.setSourceMapRange(iteratorValueStatement, node.expression); + var exitNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createFalse()); + var exitNonUserCodeStatement = factory.createExpressionStatement(exitNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var enterNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createTrue()); + var enterNonUserCodeStatement = factory.createExpressionStatement(enterNonUserCodeExpression); + ts.setSourceMapRange(exitNonUserCodeStatement, node.expression); + var statements = []; + var binding = ts.createForOfBindingStatement(factory, node.initializer, value); + statements.push(ts.visitNode(binding, visitor, ts.isStatement)); var bodyLocation; var statementsLocation; - var statements = [ts.visitNode(binding, visitor, ts.isStatement)]; var statement = ts.visitIterationBody(node.statement, visitor, context); if (ts.isBlock(statement)) { ts.addRange(statements, statement.statements); @@ -99301,8 +99520,16 @@ var ts; else { statements.push(statement); } - return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), + var body = ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* EmitFlags.NoSourceMap */ | 384 /* EmitFlags.NoTokenSourceMaps */); + return factory.createBlock([ + iteratorValueStatement, + exitNonUserCodeStatement, + factory.createTryStatement(body, + /*catchClause*/ undefined, factory.createBlock([ + enterNonUserCodeStatement + ])) + ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* FunctionFlags.Generator */ @@ -99313,6 +99540,8 @@ var ts; var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined); + var nonUserCode = factory.createTempVariable(/*recordTempVariable*/ undefined); + var done = factory.createTempVariable(hoistVariableDeclaration); var errorRecord = factory.createUniqueName("e"); var catchVariable = factory.getGeneratedNameForNode(errorRecord); var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined); @@ -99329,12 +99558,17 @@ var ts; callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement( /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([ + factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()), ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression), factory.createVariableDeclaration(result) ]), node.expression), 2097152 /* EmitFlags.NoHoisting */), - /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), + /*condition*/ factory.inlineExpressions([ + factory.createAssignment(result, createDownlevelAwait(callNext)), + factory.createAssignment(done, getDone), + factory.createLogicalNot(done) + ]), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, getValue)), + /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode)), /*location*/ node), 256 /* EmitFlags.NoTokenTrailingSourceMaps */); ts.setOriginalNode(forStatement, node); return factory.createTryStatement(factory.createBlock([ @@ -99346,7 +99580,7 @@ var ts; ]), 1 /* EmitFlags.SingleLine */)), factory.createBlock([ factory.createTryStatement( /*tryBlock*/ factory.createBlock([ - ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(getDone)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) + ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(factory.createLogicalNot(nonUserCode), factory.createLogicalNot(done)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* EmitFlags.SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([ @@ -99502,7 +99736,7 @@ var ts; /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HierarchyFacts.HasLexicalThis */))); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */ | 2048 /* NodeCheckFlags.AsyncMethodWithSuper */); + var emitSuperHelpers = languageVersion >= 2 /* ScriptTarget.ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */ | 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); @@ -99513,10 +99747,10 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = factory.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (resolver.getNodeCheckFlags(node) & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { ts.addEmitHelper(block, ts.advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.AsyncMethodWithSuper */) { + else if (resolver.getNodeCheckFlags(node) & 2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */) { ts.addEmitHelper(block, ts.asyncSuperHelper); } } @@ -99645,7 +99879,7 @@ var ts; // If we need to support substitutions for `super` in an async method, // we should track it here. if (enabledSubstitutions & 1 /* ESNextSubstitutionFlags.AsyncMethodsWithSuper */ && isSuperContainer(node)) { - var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.AsyncMethodWithSuper */ | 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */); + var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* NodeCheckFlags.MethodWithSuperPropertyAccessInAsync */ | 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */); if (superContainerFlags !== enclosingSuperContainerFlags) { var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -99722,7 +99956,7 @@ var ts; || kind === 175 /* SyntaxKind.SetAccessor */; } function createSuperElementAccessInAsyncMethod(argumentExpression, location) { - if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.AsyncMethodWithSuperBinding */) { + if (enclosingSuperContainerFlags & 4096 /* NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync */) { return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } @@ -101191,11 +101425,13 @@ var ts; return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context); } function visitIdentifier(node) { - if (!convertedLoopState) { - return node; + if (convertedLoopState) { + if (resolver.isArgumentsLocalBinding(node)) { + return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + } } - if (resolver.isArgumentsLocalBinding(node)) { - return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments")); + if (node.hasExtendedUnicodeEscape) { + return ts.setOriginalNode(ts.setTextRange(factory.createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText)), node), node); } return node; } @@ -105342,7 +105578,6 @@ var ts; return node; } function transformAndEmitForInStatement(node) { - // TODO(rbuckton): Source map locations if (containsYield(node)) { // [source] // for (var p in o) { @@ -105350,34 +105585,41 @@ var ts; // } // // [intermediate] - // .local _a, _b, _i - // _a = []; - // for (_b in o) _a.push(_b); + // .local _b, _a, _c, _i + // _b = []; + // _a = o; + // for (_c in _a) _b.push(_c); // _i = 0; // .loop incrementLabel, endLoopLabel // .mark conditionLabel - // .brfalse endLoopLabel, (_i < _a.length) - // p = _a[_i]; + // .brfalse endLoopLabel, (_i < _b.length) + // _c = _b[_i]; + // .brfalse incrementLabel, (_c in _a) + // p = _c; // /*body*/ // .mark incrementLabel - // _b++; + // _c++; // .br conditionLabel // .endloop // .mark endLoopLabel - var keysArray = declareLocal(); // _a - var key = declareLocal(); // _b + var obj = declareLocal(); // _a + var keysArray = declareLocal(); // _b + var key = declareLocal(); // _c var keysIndex = factory.createLoopVariable(); // _i var initializer = node.initializer; hoistVariableDeclaration(keysIndex); + emitAssignment(obj, ts.visitNode(node.expression, visitor, ts.isExpression)); emitAssignment(keysArray, factory.createArrayLiteralExpression()); - emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), + emitStatement(factory.createForInStatement(key, obj, factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), /*typeArguments*/ undefined, [key])))); emitAssignment(keysIndex, factory.createNumericLiteral(0)); var conditionLabel = defineLabel(); var incrementLabel = defineLabel(); - var endLabel = beginLoopBlock(incrementLabel); + var endLoopLabel = beginLoopBlock(incrementLabel); markLabel(conditionLabel); - emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitBreakWhenFalse(endLoopLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitAssignment(key, factory.createElementAccessExpression(keysArray, keysIndex)); + emitBreakWhenFalse(incrementLabel, factory.createBinaryExpression(key, 101 /* SyntaxKind.InKeyword */, obj)); var variable = void 0; if (ts.isVariableDeclarationList(initializer)) { for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) { @@ -105390,7 +105632,7 @@ var ts; variable = ts.visitNode(initializer, visitor, ts.isExpression); ts.Debug.assert(ts.isLeftHandSideExpression(variable)); } - emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex)); + emitAssignment(variable, key); transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex))); @@ -107231,7 +107473,7 @@ var ts; return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis); case ts.ModuleKind.CommonJS: default: - return createImportCallExpressionCommonJS(argument, containsLexicalThis); + return createImportCallExpressionCommonJS(argument); } } function createImportCallExpressionUMD(arg, containsLexicalThis) { @@ -107254,7 +107496,7 @@ var ts; return factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(arg), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)); } @@ -107263,7 +107505,7 @@ var ts; return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression( /*condition*/ factory.createIdentifier("__syncRequire"), /*questionToken*/ undefined, - /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), + /*whenTrue*/ createImportCallExpressionCommonJS(temp, /* isInlineable */ true), /*colonToken*/ undefined, /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis))); } @@ -107313,14 +107555,20 @@ var ts; } return promise; } - function createImportCallExpressionCommonJS(arg, containsLexicalThis) { - // import("./blah") + function createImportCallExpressionCommonJS(arg, isInlineable) { + // import(x) // emit as - // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // var _a; + // (_a = x, Promise.resolve().then(() => require(_a)) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately - var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); - var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + // If the arg is not inlineable, we have to evaluate it in the current scope with a temp var + var temp = arg && !ts.isSimpleInlineableExpression(arg) && !isInlineable ? factory.createTempVariable(hoistVariableDeclaration) : undefined; + var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), + /*typeArguments*/ undefined, + /*argumentsArray*/ []); + var requireCall = factory.createCallExpression(factory.createIdentifier("require"), + /*typeArguments*/ undefined, temp ? [temp] : arg ? [arg] : []); if (ts.getESModuleInterop(compilerOptions)) { requireCall = emitHelpers().createImportStarHelper(requireCall); } @@ -107341,14 +107589,9 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)])); - // if there is a lexical 'this' in the import call arguments, ensure we indicate - // that this new function expression indicates it captures 'this' so that the - // es2015 transformer will properly substitute 'this' with '_this'. - if (containsLexicalThis) { - ts.setEmitFlags(func, 8 /* EmitFlags.CapturesThis */); - } } - return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + var downleveledImport = factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); + return temp === undefined ? downleveledImport : factory.createCommaListExpression([factory.createAssignment(temp, arg), downleveledImport]); } function getHelperExpressionForExport(node, innerExpr) { if (!ts.getESModuleInterop(compilerOptions) || ts.getEmitFlags(node) & 67108864 /* EmitFlags.NeverApplyImportHelper */) { @@ -122521,10 +122764,16 @@ var ts; var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + // We can only reuse emit signatures (i.e. .d.ts signatures) if the .d.ts file is unchanged, + // which will eg be depedent on change in options like declarationDir and outDir options are unchanged. + // We need to look in oldState.compilerOptions, rather than oldCompilerOptions (i.e.we need to disregard useOldState) because + // oldCompilerOptions can be undefined if there was change in say module from None to some other option + // which would make useOldState as false since we can now use reference maps that are needed to track what to emit, what to check etc + // but that option change does not affect d.ts file name so emitSignatures should still be reused. var canCopyEmitSignatures = compilerOptions.composite && (oldState === null || oldState === void 0 ? void 0 : oldState.emitSignatures) && !outFilePath && - !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions); + !ts.compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); if (useOldState) { // Copy old state's changed files set (_a = oldState.changedFilesSet) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return state.changedFilesSet.add(value); }); @@ -123739,7 +123988,7 @@ var ts; var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* CharacterCodes.slash */; if (isNonDirectorySeparatorRoot && dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths - pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart + pathPartForUserCheck.search(/[a-zA-Z]\$\//) === 0) { // Dos style nextPart nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1); if (nextDirectorySeparator === -1) { // ignore "//vda1cs4850/c$/folderAtRoot" @@ -124993,7 +125242,7 @@ var ts; }); // Sort by paths closest to importing file Name directory var sortedPaths = []; - var _loop_36 = function (directory) { + var _loop_35 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (_a, fileName) { @@ -125017,9 +125266,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(importingFileName); allFileNames.size !== 0;) { - var state_12 = _loop_36(directory); + var state_11 = _loop_35(directory); directory = out_directory_1; - if (state_12 === "break") + if (state_11 === "break") break; } if (allFileNames.size) { @@ -125088,7 +125337,7 @@ var ts; } function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { for (var key in paths) { - var _loop_37 = function (patternText_1) { + var _loop_36 = function (patternText_1) { var pattern = ts.normalizePath(patternText_1); var indexOfStar = pattern.indexOf("*"); // In module resolution, if `pattern` itself has an extension, a file with that extension is looked up directly, @@ -125155,9 +125404,9 @@ var ts; }; for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { var patternText_1 = _a[_i]; - var state_13 = _loop_37(patternText_1); - if (typeof state_13 === "object") - return state_13.value; + var state_12 = _loop_36(patternText_1); + if (typeof state_12 === "object") + return state_12.value; } } function validateEnding(_a) { @@ -125245,15 +125494,21 @@ var ts; return undefined; } function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { + var normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPaths === undefined) { + return undefined; + } + var normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePaths = ts.flatMap(normalizedSourcePaths, function (sourcePath) { + return ts.map(normalizedTargetPaths, function (targetPath) { return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName)); }); + }); + var shortest = ts.min(relativePaths, ts.compareNumberOfDirectorySeparators); + if (!shortest) { return undefined; } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs - ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions) - : ts.removeFileExtension(relativePath); + ? removeExtensionAndIndexPostFix(shortest, ending, compilerOptions) + : ts.removeFileExtension(shortest); } function tryGetModuleNameAsNodeModule(_a, _b, importingSourceFile, host, options, userPreferences, packageNameOnly, overrideMode) { var path = _a.path, isRedirect = _a.isRedirect; @@ -125390,8 +125645,8 @@ var ts; } } } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { + function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.mapDefined(rootDirs, function (rootDir) { var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath; }); @@ -127959,8 +128214,15 @@ var ts; } if (buildInfo.program) { // If there are pending changes that are not emitted, project is out of date + // When there are syntax errors, changeFileSet will have list of files changed (irrespective of noEmit) + // But in case of semantic error we need special treatment. + // Checking presence of affectedFilesPendingEmit list is fast and good way to tell if there were semantic errors and file emit was blocked + // But if noEmit is true, affectedFilesPendingEmit will have file list even if there are no semantic errors to preserve list of files to be emitted when running with noEmit false + // So with noEmit set to true, check on semantic diagnostics needs to be explicit as oppose to when it is false when only files pending emit is sufficient if (((_a = buildInfo.program.changeFileSet) === null || _a === void 0 ? void 0 : _a.length) || - (!project.options.noEmit && ((_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length))) { + (!project.options.noEmit ? + (_b = buildInfo.program.affectedFilesPendingEmit) === null || _b === void 0 ? void 0 : _b.length : + ts.some(buildInfo.program.semanticDiagnosticsPerFile, ts.isArray))) { return { type: ts.UpToDateStatusType.OutOfDateBuildInfo, buildInfoFile: buildInfoPath diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index 5764216af598a..b222445278edd 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "对修饰器的实验支持功能在将来的版本中可能更改。在 \"tsconfig\" 或 \"jsconfig\" 中设置 \"experimentalDecorators\" 选项以删除此警告。", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "显示指定了模块解析类型:“{0}”。", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "除非 \"target\" 选项设置为 \"es2016\" 或更高版本,否则不能对 \"bigint\" 值执行求幂运算。", + "Export_0_from_module_1_90059": "从模块“{1}”导出“{0}”", + "Export_all_referenced_locals_90060": "导出所有引用的局部变量", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "面向 ECMAScript 模块时,不能使用导出分配。请考虑改用 \"export default\" 或另一种模块格式。", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "当 \"--module\" 标志是 \"system\" 时不支持导出分配。", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "导出声明与“{0}”的导出声明冲突。", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "使 keyof 仅返回字符串,而不是字符串、数字或符号。旧版选项。", "Make_super_call_the_first_statement_in_the_constructor_90002": "在构造函数中,使 \"super()\" 调用第一个语句", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "映射的对象类型隐式地含有 \"any\" 模板类型。", + "Matched_0_condition_1_6403": "匹配的“{0}”条件“{1}”。", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "默认情况下匹配包括模式 “**/*”", "Matched_by_include_pattern_0_in_1_1407": "通过在 \"{1}\" 中的包含模式 \"{0}\" 匹配", "Member_0_implicitly_has_an_1_type_7008": "成员“{0}”隐式包含类型“{1}”。", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "在位置“{1}”的缓存中找到模块“{0}”的解析。", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "在位置“{1}”的缓存中找到类型引用指令“{0}”的解析。", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "只将 \"keyof\" 解析为字符串值的属性名称(不含数字或符号)。", + "Resolving_in_0_mode_with_conditions_1_6402": "正在 {0} 模式下解析,条件为 {1}。", "Resolving_module_0_from_1_6086": "======== 正在从“{1}”解析模块“{0}”。========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "正在相对于基 URL“{1}”-“{2}”解析模块名“{0}”。", "Resolving_real_path_for_0_result_1_6130": "正在解析“{0}”的真实路径,结果为“{1}”。", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "为编译指定的根文件", "STRATEGY_6039": "策略", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "保存 .tsbuildinfo 文件以允许项目增量编译。", + "Saw_non_matching_condition_0_6405": "看到了不匹配的条件“{0}”。", "Scoped_package_detected_looking_in_0_6182": "检测到范围包,请在“{0}”中查看", "Selection_is_not_a_valid_statement_or_statements_95155": "所选内容不是有效的语句", "Selection_is_not_a_valid_type_node_95133": "所选内容不是有效的类型节点", @@ -1427,7 +1432,6 @@ "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362": "算术运算左侧必须是 \"any\"、\"number\"、\"bigint\" 或枚举类型。", "The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access_2779": "赋值表达式的左侧不能是可选属性访问。", "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364": "赋值表达式的左侧必须是变量或属性访问。", - "The_left_hand_side_of_an_in_expression_must_be_a_private_identifier_or_of_type_any_string_number_or__2360": "\"in\" 表达式的左侧必须是专用标识符或其类型必须为 \"any\"、\"string\"、\"number\" 或 \"symbol\"。", "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358": "\"instanceof\" 表达式左侧必须是 \"any\" 类型、对象类型或类型参数。", "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156": "向用户显示消息时所用的区域设置(例如,\"en-us\")", "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136": "用于搜索 node_modules 和加载 JavaScript 文件的最大依赖项深度。", @@ -1448,7 +1452,6 @@ "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064": "异步函数或方法的返回类型必须为全局 Promise 类型。你是否是指写入 \"Promise<{0}>\"?", "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407": "\"for...in\" 语句右侧必须是 \"any\" 类型、对象类型或类型参数,但此处的类型为“{0}”。", "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363": "算术运算右侧必须是 \"any\"、\"number\"、\"bigint\" 或枚举类型。", - "The_right_hand_side_of_an_in_expression_must_not_be_a_primitive_2361": "\"in\" 表达式的右侧不得是基元。", "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "\"instanceof\" 表达式的右侧必须属于类型 \"any\",或属于可分配给 \"Function\" 接口类型的类型。", "The_root_value_of_a_0_file_must_be_an_object_5092": "“{0}”文件的根值必须是一个对象。", "The_shadowing_declaration_of_0_is_defined_here_18017": "在此处定义了“{0}”的阴影声明", @@ -1476,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "此 JSX 标记的 \"{0}\" 属性需要 \"{1}\" 类型的子级,但提供了多个子级。", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "此 JSX 标记的 \"{0}\" 属性需要类型 \"{1}\",该类型需要多个子级,但仅提供了一个子级。", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "此比较似乎是无意的,因为类型“{0}”和“{1}”没有重叠。", + "This_condition_will_always_return_0_2845": "此条件将始终返回“{0}”。", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "此条件将始终返回“{0}”,因为 JavaScript 按引用而不是值比较对象。", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "此条件将始终返回 true,因为此“{0}”已始终定义。", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "此条件将始终返回 true,因为始终定义了函数。你是想改为调用它吗?", @@ -1551,6 +1555,7 @@ "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2412": "类型 “{0}” 不能分配给“exactOptionalPropertyTypes: true”的类型 “{1}”。请考虑将 “undefined” 添加到目标类型。。", "Type_0_is_not_comparable_to_type_1_2678": "类型“{0}”不可与类型“{1}”进行比较。", "Type_0_is_not_generic_2315": "类型“{0}”不是泛型类型。", + "Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operato_2638": "类型 \"{0}\" 可以表示基元值,该值不允许作为“in”运算符的右操作数。", "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504": "类型“{0}”必须具有返回异步迭代器的 \"[Symbol.asyncIterator]()\" 方法。", "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488": "类型“{0}”必须具有返回迭代器的 \"[Symbol.iterator]()\" 方法。", "Type_0_provides_no_match_for_the_signature_1_2658": "类型“{0}”提供的内容与签名“{1}”不匹配。", @@ -1649,9 +1654,12 @@ "Updating_output_of_project_0_6373": "正在更新项目 \"{0}\" 的输出…", "Updating_output_timestamps_of_project_0_6359": "正在更新项目“{0}”的输出时间戳...", "Updating_unchanged_output_timestamps_of_project_0_6371": "正在更新项目 \"{0}\" 未更改的输出时间戳…", + "Use_0_95174": "使用 `{0}`", + "Use_Number_isNaN_in_all_conditions_95175": "在所有条件下使用 `Number.isNaN`。", "Use_element_access_for_0_95145": "对“{0}”使用元素访问", "Use_element_access_for_all_undeclared_properties_95146": "对所有未声明的属性使用元素访问。", "Use_synthetic_default_member_95016": "使用综合的“默认”成员。", + "Using_0_subpath_1_with_target_2_6404": "将“{0}”子路径“{1}”与目标“{2}”一起使用", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "仅 ECMAScript 5 和更高版本支持在 \"for...of\" 语句中使用字符串。", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "使用 --build,-b 将使 tsc 的行为更像生成业务流程协调程序,而非编译器。这可用于触发生成复合项目,你可以在 {0} 详细了解这些项目", "Using_compiler_options_of_project_reference_redirect_0_6215": "使用项目引用重定向“{0}”的编译器选项。", diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json index 7ce669bd2f022..b53887e8cc557 100644 --- a/lib/zh-tw/diagnosticMessages.generated.json +++ b/lib/zh-tw/diagnosticMessages.generated.json @@ -660,6 +660,8 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "裝飾項目的實驗性支援是未來版本中可能會變更的功能。在 'tsconfig' 或 'jsconfig' 中設定 'experimentalDecorators' 選項可移除此警告。", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "明確指定的模組解析種類: '{0}'。", "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791": "'target' 選項必須設定為 'es2016' 或更新版本,才可以對 'bigint' 值執行乘冪運算。", + "Export_0_from_module_1_90059": "從模組 '{1}' 匯出 '{0}'", + "Export_all_referenced_locals_90060": "匯出所有參考的本機", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "當目標為 ECMAScript 模組時,無法使用匯出指派。請考慮改用 'export default' 或其他模組格式。", "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "當 '--module' 旗標為 'system' 時,不支援匯出指派。", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "匯出宣告與匯出的 '{0}' 宣告相衝突。", @@ -908,6 +910,7 @@ "Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option_6650": "僅讓 keyof 傳回字串,而不是單一字串、數字或符號。舊版選項。", "Make_super_call_the_first_statement_in_the_constructor_90002": "使 'super()' 呼叫成為建構函式中的第一個陳述式", "Mapped_object_type_implicitly_has_an_any_template_type_7039": "對應的物件類型隱含具有 'any' 範本類型。", + "Matched_0_condition_1_6403": "符合 '{0}' 條件 '{1}'。", "Matched_by_default_include_pattern_Asterisk_Asterisk_Slash_Asterisk_1457": "依預設比對包含模式 '**/*'", "Matched_by_include_pattern_0_in_1_1407": "依 '{1}' 中的包含模式 '{0}' 比對", "Member_0_implicitly_has_an_1_type_7008": "成員 '{0}' 隱含了 '{1}' 類型。", @@ -1220,6 +1223,7 @@ "Resolution_for_module_0_was_found_in_cache_from_location_1_6147": "從位置 '{1}' 的快取中找到模組 '{0}' 的解析。", "Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1_6241": "從位置 '{0}' 的快取記憶體找到類型參照指示詞 '{1}'。", "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195": "只將 'keyof' 解析為字串值的屬性名稱 (無任何數字或符號)。", + "Resolving_in_0_mode_with_conditions_1_6402": "正在以條件 {1} 在 {0} 模式中解析。", "Resolving_module_0_from_1_6086": "======== 正在從 '{1}' 解析模組 '{0}'。========", "Resolving_module_name_0_relative_to_base_url_1_2_6094": "正在解析與基底 URL '{1}' 相對的模組名稱 '{0}' - '{2}'。", "Resolving_real_path_for_0_result_1_6130": "正在解析 '{0}' 的真實路徑,結果 '{1}'。", @@ -1276,6 +1280,7 @@ "Root_file_specified_for_compilation_1427": "為編譯指定的根檔案", "STRATEGY_6039": "策略", "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642": "儲存 .tsbuildinfo 檔案,以允許對專案進行累加編譯。", + "Saw_non_matching_condition_0_6405": "儲存不相符條件 '{0}'。", "Scoped_package_detected_looking_in_0_6182": "偵測到範圍套件,正於 '{0}' 尋找", "Selection_is_not_a_valid_statement_or_statements_95155": "選取項目非有效的一或多個陳述式", "Selection_is_not_a_valid_type_node_95133": "選取範圍不是有效的類型節點", @@ -1474,6 +1479,7 @@ "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746": "此 JSX 標籤的 '{0}' 屬性只能有一個 '{1}' 類型的子系,但提供的子系卻有多個。", "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745": "此 JSX 標籤的 '{0}' 屬性需要必須有多個子系的類型 '{1}',但僅提供的子系只有一個。", "This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap_2367": "此比較似乎是無意的,因為類型 '{0}' 和 '{1}' 沒有重疊。", + "This_condition_will_always_return_0_2845": "此條件一律傳回 '{0}'。", "This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value_2839": "此條件一律會傳回 '{0}',因為 JavaScript 會依參照而非值比較物件。", "This_condition_will_always_return_true_since_this_0_is_always_defined_2801": "因為此 '{0}' 一律會被定義,所以此條件一律傳回 True。", "This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_2774": "因為永遠會定義此函式,所以此條件永遠會傳回 true。您是要改為呼叫該條件嗎?", @@ -1648,9 +1654,12 @@ "Updating_output_of_project_0_6373": "正在更新專案 '{0}' 的輸出...", "Updating_output_timestamps_of_project_0_6359": "正在更新專案 '{0}' 的輸出時間戳記...", "Updating_unchanged_output_timestamps_of_project_0_6371": "正在更新專案 '{0}' 的未更變輸出時間戳記...", + "Use_0_95174": "使用 `{0}`。", + "Use_Number_isNaN_in_all_conditions_95175": "在所有條件中都使用 'Number.isNaN'。", "Use_element_access_for_0_95145": "對 '{0}' 使用元素存取", "Use_element_access_for_all_undeclared_properties_95146": "對所有未宣告的屬性使用元素存取。", "Use_synthetic_default_member_95016": "使用綜合 'default' 成員。", + "Using_0_subpath_1_with_target_2_6404": "使用 '{0}' 子路徑 '{1}' 與目標 '{2}'。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "只有在 ECMAScript 5 及更高版本中,才可在 'for...of' 陳述式中使用字串。", "Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_tr_6915": "使用 --build、-b 會讓 tsc 的行為較編譯器更像是建置協調器。這可用於觸發建置複合專案,您可以在以下位置深入了解: {0}", "Using_compiler_options_of_project_reference_redirect_0_6215": "正在使用專案參考重新導向 '{0}' 的編譯器選項。", diff --git a/package.json b/package.json index 86b2e12d51c46..b132cb4087741 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "https://www.typescriptlang.org/", - "version": "4.9.1-beta", + "version": "4.9.2-rc", "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 e6c3def9d84bf..59cd434a58483 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: string = `${versionMajorMinor}.1-beta`; + export const version: string = `${versionMajorMinor}.2-rc`; /** * Type of objects whose values are all of the same type.